PHP MySQL Delete Data
The DELETE statement is used to delete records from a table:
DELETE FROM table_name WHERE some_column = some_value
Using MySQLi:
<?php // MySQLi Configuration $servername = "localhost"; // Change this to your MySQL server address $username = "username"; // Change this to your MySQL username $password = "password"; // Change this to your MySQL password $database = "dbname"; // Change this to your MySQL database name // Create connection $conn = new mysqli($servername, $username, $password, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Delete condition $user_id = 1; // Example condition // SQL statement for deletion $sql = "DELETE FROM users WHERE id = ?"; // Prepare the statement $stmt = $conn->prepare($sql); // Bind parameters to placeholders $stmt->bind_param("i", $user_id); // "i" represents integer data type // Execute the statement if ($stmt->execute()) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . $conn->error; } // Close statement and connection $stmt->close(); $conn->close(); ?>You can click on above box to edit the code and run again.
Output
Using PDO :
<?php // PDO Configuration $servername = "localhost"; // Change this to your MySQL server address $username = "username"; // Change this to your MySQL username $password = "password"; // Change this to your MySQL password $database = "dbname"; // Change this to your MySQL database name try { // Connect to MySQL using PDO $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password); // Set PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Delete condition $user_id = 1; // Example condition // SQL statement for deletion $sql = "DELETE FROM users WHERE id = :id"; // Prepare the statement $stmt = $conn->prepare($sql); // Bind values to named placeholders $stmt->bindParam(':id', $user_id); // Execute the statement if ($stmt->execute()) { echo "Record deleted successfully"; } else { echo "Error deleting record"; } } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } // Close connection $conn = null; ?>You can click on above box to edit the code and run again.
Output
In both examples:
Both examples will delete a record from the users table where the id column matches a specified condition (in this case, $user_id). Adjust the condition and column names as needed for your use case.