PHP/MySQL-Open and Close Connection
PHP/MySQL-Open and Close Connection
by Sagar Awasthi on Oct.06, 2009, under PHP/MySQL-Open and Close Connection
Just in brief I would like to introduce what is MySQL;
MySQL is a database and used to manage data i.e. save, delete, insert etc. The Data in MySQL is stored in database objects is called tables. A table has a collection of related data entries which is present in various coloumns and rows.
We use queries as a questioning to Database. We may say a query as a question or a request.
SELECT LastName FROM Persons
Above query object is asking for ‘lastname’ columns of table ‘Persons’.
Create a Connection to a MySQL Database
While connecting to PHP we need to connect PHP page with the database and for that we use
mysql_connect(‘[servername]’, ‘[username]’, ‘[password]’);
To Close a connection
mysql_close();
In the following example we store the mysql connection in a variable i.e $con. In if statement if connection is failed then ‘die’ will display message with an error.
Code:
<?php
$servername = ‘localhost’;
$username = ‘root’;
$password = ”;$con = mysql_connect($servername, $username, $password);
if(!$con)
{
die(’not connected…’.mysql_error());
}else{
echo(’Connected….’);
}mysql_close($con);
?>
