MySql – Connections

Connecting to the MySql database via PHP is done through the CONNECT functions.

There are two connect functions to chose from:

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); 
$link = mysql_pconnect('localhost', 'mysql_user', 'mysql_password'); 

The pconnect function will create a persistent connection to the database which will not die. The formerconnect function will not. If subsequent connection attempts are made to connect then the connect link will be refreshed and additional ones are not created. It is possible to flood the MySql server when usingpconnect and therefore its use is discouraged. Once you have connected to the MySql server you need to select the database you wish to use. This is done using the mysql_select_db function

mysql_select_db('database_name', $link); 

Obviously you should program in control measures when connecting to the database to protect your system in case the connect attempt fails . In which case the or die syntax is very helpful:

$link = mysql_connect( '', 'user', 'password')
or die('Could not connect to server.' );
$db = mysql_select_db('database_name', $link)
or die('Could not select database.');

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.