In earlier post we have seen about the combination of PHP and MySQL and in today’s post we will see some facts about MySQL and then will see how to connect to MySQL.

Before starting to how to connect MySQL , lets take some introduction to MySQL.

  •  MySQL is the most popular Open Source RDBMS : Relational Database Management System and is world’s 2nd most used open source RDBMS.
  • It was developed, supported and distributed by MySQL AB and now by Oracle.
  • MySQL is RDBMS, Open Source, Reliable, Fast ad Easy to Use.
  • It is free to download and use.
  • It works in client/Server or embedded systems and supports cross platform.
  • As of July 2013, MySQL is the most widely used open source RDBMS (Relational Database Management System) of world. Most of open source market has been covered by PHP and MySQL Combination.

Lets see how to make a connection in MySQL using PHP script.

mysql_connect :
To establish connection in MySQL using PHP we will use function named  mysql_connect() which opens the connection to MySQL Server.

Syntax :
resources mysql_connect( [ string server [ , string user_name [ , string password ] ] ]);

  •  Server is the MySQL server. It can also include a port number. For ex : “Hostname : Port”. The default value is ‘localhost : 3306’.
  • The username , default value is the name of the user that owns the server process.
  • The password. Default value is an empty password.
  • Returns a MySQL link identifier on success or FALSE on failure.

Example : 1

<?php

	$user_name = '';
	$password = '';
	$hostname = "localhost"; 

	//connection to the database
	$con = mysql_connect($hostname, $user_name, $password)  or die("Error connecting to MySQL");

			echo "Connected successfully to MySQL ";
     //close the connection
	mysql_close($con) or die ("Error while closing connection");
		echo " Connection Close successful";

?>

 

mysql_close : close the MySQL connection.

Syntax :
Boolean mysql_close ( [ resource link identifier ] )

mysql_close() closes the  connection to the MySQL server which is associated with the link identifier. If you don not specify link identifier, it automatically takes the last opened link and use that. with mysql_close(), it is not usually necessary to specify as it automatically close the connection at the end of the script.

Example : 2

<?php
     //connection to the database
	$con = mysql_connect('localhost', '', '');
	if(! $con )
	{
	  die("Could not connect: " . mysql_error());
	}
	echo "Connection successful    - " . $con;  

	//close the connection
	mysql_close($con) or die ("Error while closing connection");
		echo " Connection Close successful";
?>