Connecting to and disconnecting from MySQL

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Connecting to MySQL

Before you perform any operations, you need to connect to MySQL server and select a MySQL database.

Connecting to MySQL server from command line

Command :

MySQL -h HostName -u UserName -p





Keyword, followed by HOSTNAME.


MySQL server name


Keyword, followed by USERNAME.


MySQL user name


Asks you to enter a password.

As soon as you enter this command, it asks you to provide a password for the user you mentioned. Supplying the appropriate password would allow you to connect to MySQL server.

Connecting to MySQL database from command line

Command :

use DatabaseName;

Where DatabaseName is the database you want to select.

Disconnecting or closing MySQL server from command line

Command :


This command must be executed from the MySQL prompt.

Connecting to MySQL server and database using PHP

view plaincopy to clipboardprint?

  1. $host="localhost";  
  2. $username="root";  
  3. $password="";  
  4. $db_name="bookinfo";  
  5. $con=MySQL_connect("$host", "$username", "$password")or die("cannot connect");  
  6. MySQL_select_db("$db_name")or die("cannot select DB");  
  7. ?>  

Replace the values of the $host, $username, $password and $db_name according to your own setup. Notice that we have also selected the database with PHP, which is a must before you can fetch data from a MySQL database.

Disconnecting or closing a MySQL connection using PHP

view plaincopy to clipboardprint?

  1. MySQL_close($con);  
  2. ?>  

Where $con=MySQL_connect("$host", "$username", "$password")or die("cannot connect"), shown in the previous example.

Note : It will be convenient for you if you keep the script you require to connect to and disconnect from MySQL in a PHP file and then include that file in each PHP file you are using to perform various operations on the database.

Using MySQL persistent connection with PHP

Description :

1. MySQL persistent connection is a connection which first tries to find if any identical (i.e. with the same hostname, username, and password) exists. If so, then commands followed will use that connection. If such a connection does not exist, it would create one.

2. MySQL persistent connection does not need a MySQL_close().

PHP code :

view plaincopy to clipboardprint?

  1. $host="localhost";  
  2. $username="root";  
  3. $password="";  
  4. $db_name="bookinfo";  
  5. $con=MySQL_pconnect("$host", "$username", "$password")or die("cannot connect"); MySQL_select_db("$db_name")or die("cannot select DB");  
  6. ?>  

Note : Use MySQL_pconnect() for better performance out of your MySQL server