MySQL Database Connection

Opening Database Connection

PHP provides mysql_connect function to open a database connection. This function takes five parameters and returns a MySQL link identifier on success, or FALSE on failure.

Syntax

connection mysql_connect(server,user,passwd);

Sr.No Parameter & Description
1

server

Optional − The host name running database server. If not specified then default value is localhost:3306.

2

user

Optional − The username accessing the database. If not specified then default is the name of the user that owns the server process.

3

passwd

Optional − The password of the user accessing the database. If not specified then default is an empty password.

NOTE − You can specify server, user, passwd in php.ini file instead of using them again and again in your every PHP scripts. Check php.ini file configuration.

Example:

<?php

$dbhost = 'localhost';
$dbuser = 'username';
$dbpass = '123456';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysql_error());
}

echo 'Connected successfully';
mysql_close($conn);
?>