Deleting records in PHP

Deleting records in PHP

In PHP, you can delete records from a database using the DELETE SQL statement. The DELETE statement removes one or more rows from a table, based on a specified condition.

Here’s an example of using the DELETE statement in PHP to delete a record from a MySQL database:

// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check the connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Prepare the SQL statement
$sql = "DELETE FROM users WHERE id = 1";

// Execute the SQL statement
if (mysqli_query($conn, $sql)) {
    echo "Record deleted successfully";
} else {
    echo "Error deleting record: " . mysqli_error($conn);
}

// Close the connection
mysqli_close($conn);

In this example, the DELETE statement deletes a record from the users table where the id column equals 1. The mysqli_query() function executes the SQL statement, and the mysqli_error() function returns any error messages.

Note that the DELETE statement can be dangerous if not used carefully. Always make sure to specify a condition in the WHERE clause to avoid deleting all records in the table. Also, consider using a confirmation prompt or implementing user authentication before allowing users to delete records from the database.

Apply for PHP Certification!

https://www.vskills.in/certification/certified-php-developer

Back to Tutorials

Fetching Data for the Master
Fetching Data for the Details

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?