Delete data in MySQL. PHP function example open

Delete data in MySQL. PHP function example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

To delete data from MySQL tables use the SQL command DELETE.

DELETE FROM Table
WHERE column = value

Create a test base for the example. In which there will be columns id, name, age.

CREATE TABLE Users (id INTEGER AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30), age INTEGER)

Now let’s create a test.php file in which we will display a list of all users and links to delete their profile:

<!DOCTYPE html>
<html>

<head>
    <title>All users list</title>
    <meta charset="utf-8" />
</head>

<body>

    <?php
//create MySQL connection
$conn = mysqli_connect("localhost", "root", "password", "testdb");

//Check connection errors
if (!$conn) {
  die("Error: " . mysqli_connect_error());
}

//write SQL request
$sql = "SELECT * FROM Users";

//Let's create a table with a list of all users
if($result = mysqli_query($conn, $sql)){
    echo "<table><tr><th>Name</th><th>Age</th><th></th></tr>";
    
    foreach($result as $row){
        echo "<tr>";
            echo "<td>" . $row["name"] . "</td>";
            echo "<td>" . $row["age"] . "</td>";
            echo "<td><form action='delete.php' method='post'>
                        <input type='hidden' name='id' value='" . $row["id"] . "' />
                        <input type='submit' value='Delete'>
                   </form></td>";
        echo "</tr>";
    }
    echo "</table>";
    
mysqli_free_result($result);//clean the memory occupied by the query results

} else{
    echo "Ошибка: " . mysqli_error($conn); 
}
mysqli_close($conn);//close connection

?>
</body>

</html>
[php/]

Now let's create the file <strong>delete.php</strong>, in which the <strong>POST</strong> method will receive the id of the user whose data you want to delete:

[php]
<?php
//check if the user id has arrived
if(isset($_POST["id"]))
{
    $conn = mysqli_connect("localhost", "root", "password", "testd");

    if (!$conn) {
      die("Ошибка: " . mysqli_connect_error());
    }
//get user id
    $userid = mysqli_real_escape_string($conn, $_POST["id"]);
//sql request
    $sql = "DELETE FROM Users WHERE id = '$userid'";

    if(mysqli_query($conn, $sql)){
       echo "User deleted";
    } else{
        echo "Error: " . mysqli_error($conn);
    }
    mysqli_close($conn);    
}
?>
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation