PHP MySQL Connect to a Database

Connect to MySQL Database

Opening a connection to MySQL database from PHP is easy. Just use the mysql_connect() function like this,
Syntax

mysql_connect(servername,username,password);

servername = Specifies the server to connect to. Default value is “localhost:3306”
username = Specifies the username to log in with. Default value is the name of the user that owns the server process
password = Specifies the password to log in with. Default is “”

Example

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

Selecting Database

$dbname = ’employee’;
mysql_select_db($dbname);

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","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_close($con);
?>

Posted in Php