Cover Image for PHP MySQLi DELETE
239 views

PHP MySQLi DELETE

In PHP, you can use MySQLi (MySQL Improved) to delete data from a MySQL database table. To perform a DELETE operation, follow these steps:

  1. Connect to the MySQL Database:
    First, establish a connection to the MySQL database using the mysqli_connect() function, as shown in the INSERT and UPDATE examples.
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// Create a connection
$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check the connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
?>
  1. Prepare and Execute the DELETE Query:
    Next, prepare and execute a DELETE query to remove data from the database table. Use the mysqli_query() function to execute the query.
<?php
// Assuming you have a table named "users" with columns "id", "name", and "email"
$user_id = 1; // The ID of the user you want to delete

// Prepare the DELETE query
$sql = "DELETE FROM users WHERE id = $user_id";

// Execute the query
if (mysqli_query($conn, $sql)) {
    echo "Record deleted successfully.";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>

In this example, we are deleting a user with the ID 1 from the “users” table.

  1. Close the Database Connection:
    After executing the query, close the database connection using the mysqli_close() function to free up resources.
<?php
// Close the connection
mysqli_close($conn);
?>

As with the previous examples, always use proper data sanitization and validation techniques to prevent SQL injection and other security issues. Prepared statements or parameterized queries are safer methods to interact with the database.

Important Note: When building dynamic SQL queries with user input, use prepared statements or escape user input using functions like mysqli_real_escape_string() to prevent SQL injection attacks. Never directly embed user input in the SQL query. Also, make sure you have proper authorization checks in place before executing DELETE queries to prevent unauthorized deletions.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS