How to Delete MySQL Database using PHP

How to Delete MySQL Database using PHP


Hello folks! welcome back to a new section of our tutorial on PHP. In this tutorial guide, we are going to be discussing about how to Delete MySQL Database using PHP.

Deleting a Database

If a created database is no longer required, then it can be deleted. You can pass an SQL command to the mysql_query function for you to be able to delete a database.

Example

Try the following example below to delete a database -

<?php
   $dbhost = 'localhost:3036';
   $dbuser = 'root';
   $dbpass = 'rootpassword';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);
   
   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
   
   $sql = 'DROP DATABASE test_db';
   $retval = mysql_query( $sql, $conn );
   
   if(! $retval ) {
      die('Could not delete database db_test: ' . mysql_error());
   }
   
   echo "Database deleted successfully\n";
   
   mysql_close($conn);
?>

WARNING - It is very dangerous to delete a database and any table. So before deleting any database or table, make sure that you are doing it intentionally.


Deleting a Table

To delete a table, all you have to do is issue an SQL command to mysql_query function. But be very careful while making use of this command because doing so you can delete some important information that you have in your table.

Example

Try the following example below to delete a table -

<?php
   $dbhost = 'localhost:3036';
   $dbuser = 'root';
   $dbpass = 'rootpassword';
   $conn = mysql_connect($dbhost, $dbuser, $dbpass);
   
   if(! $conn ) {
      die('Could not connect: ' . mysql_error());
   }
   
   $sql = 'DROP TABLE employee';
   $retval = mysql_query( $sql, $conn );
   
   if(! $retval ) {
      die('Could not delete table employee: ' . mysql_error());
   }
   
   echo "Table deleted successfully\n";
   
   mysql_close($conn);
?>


Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial guide, we are going to be discussing about how to insert Data into MYSQL database using PHP.

Feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.