Child

PHP MySQL connecting script and function


Now let us start with PHP  commands to connect to MySQL server. 
$link=mysql_connect("$servername","$dbuser","$dbpassword");
Parameter Description
servername Optional. Specifies the server to connect to. Default value is "localhost:3306"
username Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process
password Optional. Specifies the password to log in with. Default is ""
 and $dbpassword is the password assign to the user id to access the mysql_server.  If successful then it will return TRUE and we can check the variable $link to check the status of the command. 
if(!$link){die("Could not connect to MySQL");}
The above command will display the error message if connection is not established.  Now once the MySQL connection established then we can select the database by using the command mysql_select_db. Here is the command.
mysql_select_db("$dbname",$link) or die ("could not open  db".mysql_error());
The above command will connect to database name stored in the variable $dbname. In case of any error the above line will print out it. Here is the total script below to connect from PHP to MySQL database using a function. At the top of the code we are assigning all values requried to connect to MySQL server.

Example

In the following example we store the connection in a variable ($con) for later use in the script. The "die" part will be executed if the connection fails:

<?php
$con = mysql_connect("localhost","mamun","123abc");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

// some code
?>


Closing a Connection

The connection will be closed automatically when the script ends. To close the connection before, use the mysql_close() function:

<?php
$con = mysql_connect("localhost","mamun","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

// some code

mysql_close($con);
?>
<?Php  // hostname or ip of server  $servername='localhost';  
// username and password to log onto db server $dbusername=''; $dbpassword='';
// name of database $dbname='mydb_name';
////////////// Do not  edit below/////////
connecttodb($servername,$dbname,$dbusername,$dbpassword); 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()); }?>
Read PHP MySQL Connection using PDO