PHP 5 Connecting to the database
How to connect database through PHP
mysql_connect() function is used to connection with the mysql server. It takes four parameter to connect the database, where first three are compulsory and last one is optional.
Syntax
$e=mysql_connect("host_name", "user_name ", "password");
Hostname: The hostname is the name of the host as listed in the MySQL server privilege tables. If the database is on the same computer as PHP, you should use localhost as the hostname.
User Name: You must provide a valid user name that can be used to access the database.
Password: You have a valid password to access the database. The database administrator sets this up.
Note: If Database on same server as web server, can use "localhost" as the host name.
If more than 1 connection needed to same host with same username/password, add TRUE as a 4th parameter
Example of mysql_connect() function
<?php $user = "root"; $pwd = " "; $host = "localhost"; $var_con = @mysql_connect($host, $user, $pwd); if($var_con) { echo "Successfully connected"; } else { echo"connection fail"; } ?>
Output
Explanation
It's return TRUE if connection successful otherwise return FALSE.
Note: Password field are blank because we did not choose any password.
The @ symbol in front of mysql_connect() informs to this function, if the Database connection failed do nothing. Hence no system error will be displayed if database connection fails.
Another example of database connection by using mysql_connect() function
<?php @$db = mysql_connect("localhost","root",""); if (!$db) echo "Could not connect to the database"; else echo "Connected";
?>
Output
How to close the database connection
Once you have done all the query to the mysql server, you should close the dadabase connection. You can close database connection by using mysql_close() function.
Syntax of database close function
If connection variable not specified, mysql_close() close the most recently open database.
Example of closing database
<?php $user = "root"; $pwd = " "; $host = "localhost"; $var_con = @mysql_connect($host, $user, $pwd); if($var_con) { echo "Successfully connected"; } else { echo "connection fail"; } @mysql_close(); //it's close the database ?>
Note: In above case there is no need to specify connection variable because only one server connection establish.