In this tutorial you will learn about the MySQL Connection and its application with practical example.
Before you perform any operations, you need to connect to MySQL server and select a MySQL database.
Table Of Contents−
Connecting to MySQL server and database using PHP
PHP uses mysql_connect() function to open a database connection.Here is prototype for mysql_connect() function.
1 |
mysql_connect("$host", "$username", "$password"); |
Parameter | Description |
---|---|
Host | The host name running database server. for using on local installation we use “localhost” as host name |
username | The username accessing the database. for “localhost” dafualt username is “root“ |
password | The password of the user accessing the database. If not specified then default is an empty password. |
1 2 3 4 5 6 7 8 |
<?php $host="localhost"; $username="root"; $password=""; $db_name="emp_db"; $con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); ?> |
MySQL persistent connection with PHP
MySQL persistent connection is a connection which first tries to find if any identical connection (i.e with 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. MySQL persistent connection can not be close using mysql_close(). Persistent connection is used for better performance out of your MySQL server
1 2 3 4 5 6 7 8 |
<?php $host="localhost"; $username="root"; $password=""; $db_name="emp_db"; $con=mysql_pconnect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); ?> |
Disconnecting or closing a MySQL connection using PHP
1 2 3 |
<?php mysql_close($con); ?> |