PHP MySQL Connecting string

Connection to Mysql database can be established by using mysql_connect function. We can check the success of the function by checking the result. We will get a true result in case connection is established. Based on this we can even print a message saying the details. This function takes three parameters, first one is hostname then user-id and them password. We can give the port number along with the hostname also.

Here is the function to connect to mysql database
mysql_connect ("$servername","$dbuser","$dbpassword");
The above function will return true or false depending on the success of the connection. So we will add message to the above function like this.
$link=mysql_connect ("$servername","$dbuser","$dbpassword");
if(!$link){die("Could not connect to MySQL");}
Mysql_connect once establish the connection the link will be present till the script execution is over. It will close it self once the script execution is over or the function mysql_close() is called.

Connecting string with database selection. mysql_select_db() function
We can create a connection string and database connections at one go. This is required where all over the script we are using one database so better to select the database just after the connection is established. Here is the code.

// username and password to log onto db server
// name of database

////// DONOT EDIT BELOW  ///////// 

function connecttodb($servername,$dbname,$dbuser,$dbpassword)
global $link;
$link=mysql_connect ("$servername","$dbuser","$dbpassword");
if(!$link){die("Could not connect to MySQL");}
mysql_select_db("$dbname",$link) or die ("could not open db".mysql_error());

PHP MySQL Persistence Connection

Mysql_pconnect works same as mysql_connect with two differences. Mysql_pconnect function keeps the connection live even the script execution is over. It does not close the connection like mysql_connect case where it closes the connection once the script execution is over. The other difference is it tries to find any existing connection exists and return a identifier if exists.

The main purpose of using mysql_pconnect function is to maintain a persistence connection to the mysql server. Function mysql_close() can't close persistent connection.
mysql_pconnect ("$servername","$dbuser","$dbpassword");

PHP PDO connection to MySQL Database

PHP MYSQLI connection string


* indicates required
Subscribe to plus2net



    nice working
    Craig Misak


    I think you have a typo.... you define $dbusername='userid' but than further down in your mysql_connect its only $dbuser.. I'm a newbe so maybe there is something else going on

    Post your comments , suggestion , error , requirements etc here .

    SQL Video Tutorials

    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2022 All rights reserved worldwide Privacy Policy Disclaimer