How to test MySQL database connection

You can test connectivity to a MySQL database using the below sample script:

        <?php
        $dbname = 'mysql_dbname';
        if (!mysql_connect('mysql_host',        'mysql_user', 'mysql_password')) {
            echo 'Could not connect to mysql'; exit;
        }
        $sql = "SHOW TABLES FROM $dbname";
        $result = mysql_query($sql);
        if (!$result) {
            echo "DB Error, could not list tables\n";
            echo 'MySQL Error: ' . mysql_error(); exit;
        }
        while ($row = mysql_fetch_row($result)) {
            echo "Table: {$row<span class="error">[0]</span>}\n";
        }
        mysql_free_result($result);
        ?>

The variables used in the script are:
mysql_dbname: the MySQL database name
mysql_host: this needs to be specified as localhost
mysql_user: the username associated with the above MySQL database
mysql_password: the password corresponding to the above user

This script, on a successful connection, will fetch and display the names of all the tables in the specified database.