Php-mysql Course

PDO (PHP Data Objects) is a PHP extension for accessing databases in PHP.
PDO uses OOP characteristics (Object Oriented Programming) available since PHP 5.1.
Because PDO is working with classes and objects, you must be familiar with the PHP object-oriented programming.
PDO can work with the following databases:

- One of the PDO advantages is that you can use similar functions for processing queries to databases, regardless of their type (of those mentioned above).
The PHP scripts that use PDO to connect to a database perform in general the following operations:
  1. Connect to the database server by calling new PDO(), that creates an object for working with that database.
  2. Implementing PDO specific functions to perform queries to the database.
  3. Getting and processing the returned data.
  4. Disconnect from the database server.
- To see if the PDO is available in your PHP server, for your database, you can check with phpinfo(), where it's a section for PDO, or with this method: PDO::getAvailableDrivers()
foreach(PDO::getAvailableDrivers() as $driver) {
  echo $driver.'<br />';
}

Connecting to database

Any interaction with a database begins by connecting to it. Depending on the type of database, the connection is made by creating an instance object, with: new PDO(). After the connection is created, we apply PDO methods to get and process data. These methods are largely the same, regardless of the connected database. Here is how to connect to some of these database:

Connecting to MySQL

<?php
// Connection data (server_address, database, username, password)
$hostdb = 'localhost';
$namedb = 'dbname';
$userdb = 'username';
$passdb = 'password';

// Display message if successfully connect, otherwise retains and outputs the potential error
try {
  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
  echo 'Connected to database';
}
catch(PDOException $e) {
  echo $e->getMessage();
}
?>
- The $conn variable is the PDO object that will contain the data received from MySQL server. The PDO methods for processing data will be aplied to this object.
Notice this statement: try() ... catch() This is used to not expose important connection data that can be displayed in case of errors.
        - For example, using this technique if your database name is incorrect, returns something like this:
SQLSTATE[42000] [1049] Unknown database 'dbname'
        - If the name or password is wrong, show something similar to:
SQLSTATE[28000] [1045] Access denied for user 'username'@'localhost' (using password: YES)
But if you use directly:
<?php
// Connection data (server_address, database, username, password)
$hostdb = 'localhost';
$namedb = 'dbname';
$userdb = 'username';
$passdb = 'password';

$conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
?>
        - The error message would display more data, including password, as shown below:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[28000] [1045] Access denied for user 'thename'@'localhost' (using password: YES)' in E:\server\www\zzz.php:14 Stack trace: #0 E:\server\www\zzz.php(14): PDO->__construct('mysql:host=loca...', 'thenae', 'the_password') #1 {main} thrown in E:\server\www\zzz.php on line 7
So it is recommended to apply try() ... catch().

Connecting to PostgreSQL

<?php
try {
  $conn = new PDO("pgsql:host=localhost port=5432 dbname=pdo", "username", "password");
  echo "PDO connection object created";
}
catch(PDOException $e) {
  echo $e->getMessage();
}
?>

Connecting to SQLite

When PDO is used with SQLite, you specify only the path to your file with the database. If that file not exist, it will try to create it.
<?php
try {
  // connect to SQLite database
  $conn = new PDO("sqlite:/path/to/database.sdb");
}
catch(PDOException $e) {
  echo $e->getMessage();
}
?>

Connecting to Firebird

Firebird is a database used in Windows.
<?php
try {
  $conn = new PDO("firebird:dbname=localhost:C:\Programs\Firebird\DATABASE.FDB", "SYSDBA", "masterkey");
}   
catch (PDOException $e) {
  echo $e->getMessage();
}
?>

Connecting to Informix

<?php
try {
  $conn = new PDO("informix:DSN=InformixDB", "username", "password");
}
catch (PDOException $e) {
  echo $e->getMessage();
}
?>

Connecting to Oracle

<?php
try {
  $conn = new PDO("OCI:dbname=accounts;charset=UTF-8", "username", "password")
}
catch (PDOException $e) {
  echo $e->getMessage();
}
?>

Connecting to ODBC

There are many ODBC connections that can be created. Here's how to connect to a MS Access database called "accounts".
<?php
try {
  $conn = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\accounts.mdb;Uid=Admin");
}
catch (PDOException $e) {
  echo $e->getMessage();
}
?>

Connecting to DBLIB

Another database for Windows.
<?php
$hostdb = "localhost";
$port   = 10060;
$namedb   = "my_database";
$userdb = "username";
$passdb = "password";

try {
  $conn = new PDO ("dblib:host=$hostdb:$port;dbname=$namedb","$userdb","$passdb");
}
catch (PDOException $e) {
  echo $e->getMessage();
}
?>

Connecting to IBM

The following example shows how to connect to a IBM DB2 database, named "accounts".
<?php
try {
  $conn = new PDO("ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=accounts; HOSTNAME=1.2.3,4;PORT=56789;PROTOCOL=TCPIP;", "username", "password");
}
catch (PDOException $e) {
  echo $e->getMessage();
}
?>

Close the connection to database

Normally, PHP closes the connection to the database after the script was executed. But the disconnection can be done intentionally, attributing the null value to the PDO object, as it's shown in the example below.
The instance of that object will be destroyed, so, this method should be added after all the instructions at the PDO object were written.
    -Disconnecting with this method is useful because it releases the memory used.

<?php
// Connection data (server_address, database, username, password)
$hostdb = 'localhost';
$namedb = 'dbname';
$userdb = 'username';
$passdb = 'password';

// Display message if successfully connect, otherwise retains and outputs the potential error
try {
  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
  echo 'Connected to database';
     /* Instructions for working with $conn object */

  $conn = null;         // Close the connection
}
catch(PDOException $e) {
  echo $e->getMessage();
}
?>

In the next lesson it is presented how to add data in a MySQL database, INSERT, UPDATE, and DELETE, using the PDO exec() method.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
PHP PDO - Introduction and Connecting to Databases

Last accessed pages

  1. Pencil and Pen Tools (2262)
  2. Graphic Symbols (1512)
  3. CSS cursor property - Custom Cursors (6184)
  4. Responses (329)
  5. Add sounds and audio effects in Flash (3540)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (523)
  2. The Mastery of Love (65)
  3. CSS cursor property - Custom Cursors (63)
  4. Read Excel file data in PHP - PhpExcelReader (59)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (44)