PHP Connect to MySQL Database

Posted by tutor | Posted in PHP Tutorial | Posted on 18-12-2009-05-2008

0

For using a database, first you need to install a database, then there must be a database with the desired tables you wish to use. Finally there should be data in the tables which you will be using in your application.

The second major step then is to access the data through the database in your application.
For accessing data in a database, you must create a connection to the database. A connection is the gateway through which your request will go to the database and the result will be provided to you from the database.

In PHP, this is done with the mysql_connect() function.

Syntax

    mysql_connect(servername,username,password);
    Parameter

    servername

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

In the following example we store the connection in a variable ($con) for later use in the script. The “die” part will be executed if the connection fails:

    For eg:

    <?php
    $con = mysql_connect(”localhost”,”peter”,”abc123″);
    if (!$con)
    {
    die(’Could not connect to database: ‘ . mysql_error());
    }
    // some code
    ?>

Closing a Connection

The connection that is created and opened to access data in a database will be closed automatically when the script ends. But you can close it as soon as the database related work is done. To close the connection through your code you can use the mysql_close() function:

    <?php
    $conn = mysql_connect(”localhost”,”tutor”,”tutor123″);
    if (!$conn)
    {
    die(’Could not connect to database: ‘ . mysql_error());
    }
    // some code
    mysql_close($conn);
    ?>

Write a comment

Twitter Users
Enter your personal information in the form or sign in with your Twitter account by clicking the button below.