Supprimer les données d'une table MySQL avec MySQLi et AOP
L'instruction DELETE est utilisée pour supprimer des enregistrements d'une table:
DELETE FROM table_name
WHERE some_column = some_value
Notez la clause WHERE dans la syntaxe SUPPRIMER: La clause WHERE spécifie quels ou des documents qui doivent être supprimés. Si vous omettez la clause WHERE, tous les enregistrements seront supprimés!
Pour en savoir plus sur SQL, s'il vous plaît visitez notre tutoriel SQL .
Regardons la "MyGuests" tableau:
ça | Prénom | nom de famille | reg_date | |
---|---|---|---|---|
1 | John | Biche | [email protected] | 22/10/2014 14:26:15 |
2 | Marie | Moe | [email protected] | 23/10/2014 10:22:30 |
3 | Julie | Dooley | [email protected] | 26/10/2014 10:48:23 |
Les exemples suivants supprimer l'enregistrement avec id = 3 dans le "MyGuests" tableau:
Exemple (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password =
"password";
$dbname =
"myDB";
// Create connection
$conn =
new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql
= "DELETE FROM MyGuests WHERE id=3";
if ($conn->query($sql) === TRUE) {
echo "Record
deleted successfully";
} else {
echo
"Error deleting record: " . $conn->error;
}
$conn->close();
?>
Exemple (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password =
"password";
$dbname =
"myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection
failed: " . mysqli_connect_error());
}
// sql to delete a
record
$sql
= "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted
successfully";
} else {
echo "Error
deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Exemple (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname =
"myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
// sql to delete a record
$sql
= "DELETE FROM MyGuests WHERE id=3";
// use exec() because no
results are returned
$conn->exec($sql);
echo "Record deleted successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Après l'enregistrement est supprimé, la table ressemblera à ceci:
ça | Prénom | nom de famille | reg_date | |
---|---|---|---|---|
1 | John | Biche | [email protected] | 22/10/2014 14:26:15 |
2 | Marie | Moe | [email protected] | 23/10/2014 10:22:30 |