PHP - Connecting to MySQL Database

    Opening Connection

    Before starting, first, we have to make a connection to the database from the PHP code so that we can interact with the database and play with the data around. PHP allows you to use mysql_connect function that allows you to create a connection with your database. This function will use five different parameters to start working. It will return the MySQL link identifier if the connection is successful else return false ob failing.

    Although all the parameters are optional, one should know what could be the possible values for these parameters. You can avoid passing user name, password, and server details every time instead you can make changes in the php.ini file.


    Connection mysql_connect(server,user,passwd,new_link,client_flag);
    Parameter Description
    server Specifies the hostname that is running the server and default value is localhost:3306.
    user Specifies the name of the user accessing the database which uses the user name using the server by default.
    passwd The password belongs to the above-mentioned user.
    new_link No new connection will be made if the function is called again to connect to the database.
    • MYSQL_CLIENT_SSL ? specifies SSL encryption
    • MYSQL_CLIENT_COMPRESS ? specifies compression protocol
    • MYSQL_CLIENT_IGNORE_SPACE ? ignore space after function names
    • MYSQL_CLIENT_INTERACTIVE ? ensures timeout due to any inactivity before the connection is closed.

    Closing connection

    If you have opened a connection to the database then it is important that you close the connection to avoid resource consumption. PHP allows you to use mysql_close function to solve the purpose which returns the true value on success and false if the function call fails. It is important that you specify what connection you want to end else the last opened connection will get closed by default.


    bool mysql_close ( $link_identifier );


    $db_host = 'localhost:3036';
    $db_user = 'guest';
    $db_pass = 'guest123';
    $conn_db = mysql_connect($db_host, $db_user, $db_pass);
    if(! $conn_db ) {
    die('Connection failed: ' . mysql_error());
    echo 'Success';

    People are also reading: