1To delete data from a table, you use the MySQL DELETE statement. The following illustrates the syntax of the DELETE statement:
2
3DELETE FROM table_name
4WHERE condition;
5In this statement:
6
7First, specify the table from which you delete data.
8Second, use a condition to specify which rows to delete in the WHERE clause. The DELETE statement will delete rows that match the condition,
1
2<?php
3$servername = "localhost";
4$username = "username";
5$password =
6 "password";
7$dbname =
8 "myDB";
9
10// Create connection
11$conn =
12 new mysqli($servername, $username, $password, $dbname);
13
14 // Check connection
15
16 if ($conn->connect_error) {
17
18 die("Connection failed: " . $conn->connect_error);
19}
20
21
22
23// sql to delete a record
24
25 $sql
26 = "DELETE FROM MyGuests WHERE id=3";
27
28
29if ($conn->query($sql) === TRUE) {
30 echo "Record
31 deleted successfully";
32} else {
33 echo
34 "Error deleting record: " . $conn->error;
35}
36
37$conn->close();
38
39?>
40
1
2<?php
3$servername = "localhost";
4$username = "username";
5$password =
6 "password";
7$dbname =
8 "myDB";
9
10// Create connection
11
12$conn = mysqli_connect($servername, $username, $password,
13 $dbname);
14
15 // Check connection
16
17 if (!$conn) {
18
19 die("Connection
20 failed: " . mysqli_connect_error());
21}
22
23// sql to delete a
24 record
25
26 $sql
27 = "DELETE FROM MyGuests WHERE id=3";
28
29
30if (mysqli_query($conn, $sql)) {
31 echo "Record deleted
32 successfully";
33} else {
34 echo "Error
35 deleting record: " . mysqli_error($conn);
36}
37
38mysqli_close($conn);
39
40?>
41
1
2<?php
3$servername = "localhost";
4$username = "username";
5
6 $password = "password";
7$dbname =
8 "myDBPDO";
9
10try {
11 $conn = new PDO("mysql:host=$servername;dbname=$dbname",
12 $username, $password);
13
14 // set the PDO error mode to exception
15 $conn->setAttribute(PDO::ATTR_ERRMODE,
16 PDO::ERRMODE_EXCEPTION);
17
18 // sql to delete a record
19
20
21 $sql
22 = "DELETE FROM MyGuests WHERE id=3";
23
24
25 // use exec() because no
26 results are returned
27 $conn->exec($sql);
28
29 echo "Record deleted successfully";
30 }
31catch(PDOException $e)
32 {
33
34 echo $sql . "<br>" . $e->getMessage();
35 }
36
37
38$conn = null;
39
40?>
41