w3resource logo
MySQL Tutorial

MySQL Connection

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 

Parameters

Name Description
-h Keyword, followed by HOSTNAME.
HostName MySQL server name
-u Keyword, followed by USERNAME.
UserName MySQL user name
-p 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:

exit

This command must be executed from the MySQL prompt.

Connecting to MySQL server and database using PHP

<?php
$host="localhost";
$username="root";
$password="";
$db_name="bookinfo";
$con=MySQL_connect("$host", "$username", "$password")or die("cannot connect");
MySQL_select_db("$db_name")or die("cannot select DB");
?>

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

<?php
MySQL_close($con);
?>

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:

<?php
$host="localhost";
$username="root";
$password="";
$db_name="bookinfo";
$con=MySQL_pconnect("$host", "$username", "$password")or die("cannot connect"); MySQL_select_db("$db_name")or die("cannot select DB");
?>

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