Oj Obasi
Oj Obasi

I am also and will continue to be a student of web design and development. My tutorials may not be for you. If you feel that way, then search online for better tutorials.

PHP PDO Connect to MySQL

In this tutorial we will be connecting to our mysql database in php. There are two principle ways you can achieve this in php:-

1. MySQLi

2. PDO (PHP Data Objects)

In this tutorial , we will be using the later (PDO). You can use which ever you prefer but for us for many reasons , we would be using PDO.

One of the reasons being that most of our php tutorials here would be based on the PDO API.

Both MySQLi and PDO have their advantages and disadvantages.

Both are object-oriented, but MySQLi also offers a procedural API.

Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very important for web application security.

connect to database code:

<?php
define("DB_HOST","localhost"); // for most
define("DB_NAME","YOUR_DATABASE_NAME_HERE");
define("DB_PORT","3306"); // default: 3306 The port number where the database server is listening.
define("DB_USER","YOUR_USERNAME_HERE");
define("DB_PASS","YOUR_USER_PASSWORD_HERE");
try {
$db = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME .";port=" . DB_PORT,DB_USER,DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
echo 'Hurray! connected'; // to make sure its successful
} catch (Exception $e) {
echo "Could not connect to the database.";
exit;
}
?>

AWESOMENESS OF PDO ( try{ } and catch{ } blocks)

PDO has an exception class to handle any problems(ERRORS) that may occur in our database queries. If an exception is thrown within the try{ } block, the script stops executing and flows directly to the first catch(){ } block.

NOTE:$db->exec("SET NAMES 'utf8'");

Our code can only be used with character sets that share the same lower 7 bit representation as ASCII, such as ISO-8859-1 and UTF-8. Users using character sets that have different representations (such as UTF-16 or Big5) must use the charset option provided in PHP 5.3.6 and later versions.(http://php.net/).

Prior to PHP version 5.3.6, charset was ignored.