Connecting to MySQL

Connections are established by creating instances of the PDO base class. It doesn't matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any).

Old Way

<?php

$link = mysql_connect('localhost', 'user', 'pass');

mysql_select_db('testdb', $link);
mysql_set_charset('UTF-8', $link);

new way: all you gotta do is create a new PDO object. PDO's constructor takes at most 4 parameters, DSN, username, password, and an array of driver options.

Example #1 Connecting to MySQL

<?php

$host = 'localhost';
$database = 'test';
$username = 'database_username';
$password = 'database_password';
$charset = 'utf8';

$dbh = new PDO("mysql:host=$host;dbname=$database;charset=$charset", $username, $password);

?>

If there are any connection errors, a PDOException object will be thrown. You may catch the exception if you want to handle the error condition, or you may opt to leave it for an application global exception handler that you set up via set_exception_handler().

Example #2 Handling connection errors

<?php

try {

    $host = 'localhost';
    $database = 'test';
    $username = 'database_username';
    $password = 'database_password';
    $charset = 'utf8';

    $dbh = new PDO("mysql:host=$host;dbname=$database;charset=$charset", $username, $password);

    foreach($dbh->query('SELECT * from TABLE_NAME') as $row) {
        print_r($row);
    }

    $dbh = null;

} catch (PDOException $e) {

    print "Error!: " . $e->getMessage() . "<br/>";
    die();

}

?>

Important Part:  if you are running live website . Do not use Try Catch error, it may leak some information, that you may not wish to be seen by your user. Thus Configure PHP for proper error reporting :-

  • on a live site set display_errors=off and log_errors=on
  • on a development site, you may want to set display_errors=on
  • of course, error_reporting has to be set to E_ALL in both cases

On a development server just turn displaying errors on:

ini_set('display_errors', 1);

While on a production server turn displaying errors off while logging errors on:

ini_set('display_errors', 0);
ini_set('log_errors', 1);
  • keep in mind that there are other errors that shouldn't be revealed to the user as well.

Loading ...

Related Results :

  1. Connecting to MySQL
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author