Home >>MySQL Tutorial >PHP MySQL Connectivity

PHP MySQL Connectivity

PHP Mysql connectivity

Use the mysql_connect( ) function to established connection to the MySQL server. To access the database functionality we have to make a connection to database using Php. mysql_connect() function is used to establish the connection to mysql server.

Four arguments need to be passed to mysql_connect() function.

Hostname : if you are working on local system , you can use localhost or you can also provide ip address or server name.
username : if there is a existing user , you can provide username. default username is 'root'.
password : by default password is blank or null.
dbname : it is a optional field . it is basically a name of the database that need to be connected.
mysql_connect(host, username, password, dbname);
Parameter Description
host(Server name) Either a host name(server name) or an IP address
username The MySQL user name
password The password to log in with
dbname Optional. The database to be used when performing queries

  Note : There are more available parameters, but the ones listed above are the most important. In the following example we store the connection in a variable ($con) for later use in the script

<?php

// Create connection
$con=mysql_connect("localhost","root","") or die(mysql_error());

?>

Here localhost is server name. root is MySQL default user name. default password is blank and database name is my_db. mysql_error( ) function provides mysql connectivity error message.

MySQL Close Connection

<?php
// Create connection
 $con=mysql_connect("localhost","root","","my_db") or die(mysql_error());	
//code to be executed...

// Close connection	
mysql_close($con);
   
?>

after work with the database is done we have to close the connection using mysql_close() function in which the connection to the database is passed.


No Sidebar ads