MySQL Delete Data

Deleting data in a MySQL table using PHP involves executing an SQL DELETE query. You can either use the procedural or object-oriented approach for interacting with the database.


Syntax:


DELETE FROM table_name WHERE condition;


The following example updates the name and age of the user with id=1.

Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Delete query
$sql = "DELETE FROM users WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
// Close connection
$conn->close();
?>

Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase"; // Change to your database name
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Delete query
$sql = "DELETE FROM users WHERE id=1";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>

Example (PDO)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// Set PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Delete query with placeholders
$sql = "DELETE FROM users WHERE id=:id";
// Prepare statement
$stmt = $conn->prepare($sql);
// Bind parameter
$stmt->bindParam(':id', $id);
// Value to delete
$id = 1;
// Execute delete
$stmt->execute();
echo "Record deleted successfully";
} catch (PDOException $e) {
echo "Error deleting record: " . $e->getMessage();
}
// Close connection
$conn = null;
?>

Note

Without a WHERE clause, all records in the table would be deleted. Make sure to specify which row(s) you want to delete.


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.