Create a Connection to a Mysql Database

In order to access data in a database, you must create first a connection to your database.

In PHP, this is done with the mysql_connect() function.

Syntax:
mysql_connect(servername,username,password);

Parameter Description
servername Optional. Specifies the server to connect to.
Default value is “localhost:3306”
username Optional. Specifies the useranme 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 “”.

 

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”,”root”,”123″);
if(!con)
{
die(‘could not connect:’.mysql_error());
}
?>

 
Closing a Connection

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

<?php
$con=mysql_connect(“localhost”,”root”,”123″);
if(!con)
{
die(‘could not connect:’.mysql_error());
}

//create database
if(mysql_query(“CREATE DATABASE sampledata”,$con))
{
echo “database created”;
}
else
{
echo “error creating database:”.mysql_error();
}
mysql_close($con);

?>