PHP MySQL DELETE QUERY
To perform a DELETE
query in PHP using MySQLi in procedural style, follow these steps:
1. Establish a Database Connection
First, connect to the MySQL database using mysqli_connect()
.
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
2. Prepare the DELETE
Query
Construct the SQL DELETE
query string. For example, if you want to delete a record from a table named users
where the username
is 'john_doe'
, your query might look like this:
$sql = "DELETE FROM users WHERE username = 'john_doe'";
3. Execute the Query
Use mysqli_query()
to execute the DELETE
query.
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
4. Close the Database Connection
After executing the query, close the connection using mysqli_close()
.
mysqli_close($conn);
Full Example
Here’s a complete example of a DELETE
query using MySQLi in procedural style:
<?php
// Step 1: Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Step 2: Prepare the DELETE query
$sql = "DELETE FROM users WHERE username = 'john_doe'";
// Step 3: Execute the query
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
// Step 4: Close the connection
mysqli_close($conn);
?>
Notes
- Error Handling: Always check if
mysqli_query()
returnsfalse
to handle potential errors in the query execution. - Escaping Strings: If the condition involves user input, use
mysqli_real_escape_string()
to escape special characters in the input values before including them in your query to prevent SQL injection attacks. - Prepared Statements: For better security, especially when dealing with user input, consider using prepared statements with
mysqli_prepare()
andmysqli_stmt_bind_param()
.
Here’s an example using prepared statements for the DELETE
query:
<?php
// Step 1: Connect to the database
$conn = mysqli_connect('localhost', 'username', 'password', 'database');
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Step 2: Prepare the DELETE query
$stmt = mysqli_prepare($conn, "DELETE FROM users WHERE username = ?");
// Bind parameters
mysqli_stmt_bind_param($stmt, "s", $username);
// Set parameters and execute
$username = 'john_doe';
mysqli_stmt_execute($stmt);
if (mysqli_stmt_affected_rows($stmt) > 0) {
echo "Record deleted successfully";
} else {
echo "No record deleted or an error occurred";
}
// Close the statement and connection
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>