Before you can access data in a database, you must create a connection to the database. In PHP, this is done with the mysql_connect() function.

Syntax:

mysql_connect($server, $username, $password, $new_link, $client_flags);

Where the parameters, $server specifies the server name, $username specifies the username, $password specifies the password, $new_link is used If a second call is made to mysql_connect with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned(it is optional parameter) and $client_flags is optional parameter which specifies a combination of the following constants: 128 (enable LOAD DATA LOCAL handling), MYSQL_CLIENT_SSL etc.

Let’s have an example, how to create connection with MySQL database server in PHP.

Example: Creating connection with MySQL database
<?php
    // creatingconnection with mysql database server
 
    $con = mysql_connect("localhost", "root", "root");
    // check connection is establish or not
    if(!$con)
    {
        die ("Connectionnot established! Please try again");
    }
    else
    {
        echo 'Connection successfully created.';
    }
?>

Now debug the above PHP script, output will be.

Connecting PHP script with MySQL

Example: Closing a connection

If you do not close connection then connection will be close automatically after the executing script. But if you want to close a connection before finishing the script then write the following code:

Syntax:

mysql_close($conVariable);

 

<?php
    // creatingconnection with mysql database server
 
    $con = mysql_connect("localhost", "root", "root");
    // check connection is establish or not
    if(!$con)
    {
        die ("Connectionnot established! Please try again");
    }
    // write code
 
    // Closing the connection
    mysql_close($con);
    echo 'Connection closed successfully';
?>
Output:

Connecting PHP script with MySQL

So this is the simple way through which we can create connection and close connection with MySQL database server.


  Modified On Nov-30-2017 12:02:57 AM

Leave Comment