How to Delete Data from MySQL Database
In order to manipulate and the database and make some correction, you have to remove the unused data from the database. If you want to make some correction, you need to delete data from the database to maintain the accuracy of the database.
Now, to delete the data from the MySQL database, you have to first create MySQL deletion query. After that, you have to execute the query using the PHP functions. There are two alternatives you can use in PHP to delete data into MySQL databases.
- mysqli_query()
- PDO::__query()
The mysqli_query() is a simple function you can use to delete the data from the MySQL database. If you need to use another database in the future, you can use another PHP function called PDO function as PDO supports more than twelve different types of databases.
Delete Data Using MySQLi Procedural
To delete data from the database, you have to create a query using the condition to delete the data from the table of the database. You can follow and use the examples given below.
The PHP function is same but only the query is different containing the delete query statement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
$hostname = "localhost"; $username = "root"; $password = ""; $mydbname = "test" //make connection $dbconn = mysqli_connect($hostname,$username,$password,$mydbname); //check connection if(!$dbconn) { die("Connection Error: ".mysqli_connect_error()); } //create query $sql = "delete from user where id=1"; //execute query and delete data if(mysqli_query($dbconn, $sql)){ echo "Data deleted successfully"; }else{ echo "Could not delete data " . mysqli_error($dbconn); } //close connection mysqli_close($dbconn); |
Delete data using MySQLi Object-oriented
Object-oriented is the best practice to use in your project and delete the data from the database. You can delete the data from the database by using the deletion query and execute it by using PHP object-oriented programming.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
$hostname = "localhost"; $username = "root"; $password = ""; $mydbname = "test" //make connection $dbconn = new mysqli($hostname,$username,$password,$mydbname); //check connection if($dbconn->connect_error) { die("Connection Error: ".$dbconn->connect_error); } //create query $sql = "delete from user where id=1"; //execute query and delete data if($dbconn->query($sql)){ echo "Data deleted successfully"; }else{ echo "Data deletion failed ".$dbconn->connect_error; } //close connection $dbconn->close(); |