Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
POD vs mysql_function?
#1
PDO, the PHP Data Objects extension, is a data-access abstraction layer. Basically, it’s a consistent interface for multiple databases. No longer will you have to use the mysql_* functions, the sqlite_* functions, or the pg_* functions, or write wrappers for them to work with your database. Instead, you can simply use the PDO interface to work with all three functions using the same methods. And, if you change databases, you’ll only have to change the DSN (or Data Source Name) of the PDO to make your code work.

PDO uses specific database drivers to interact with various databases, so you can’t use PDO by itself. You’ll need to enable the drivers you’ll use with PDO, so be sure to research how to do it for your specific host operating system on the PDO manual page.

PDO is shipped with PHP 5.1 and is available from PECL for PHP 5.0. Unfortunately, as PDO requires the new PHP 5 object oriented features, it’s not available for PHP 4. In this blog, all of our interactions with the database will use PDO to interact with the MySQL back end.

How do I access a database?

Before we can do anything with a database, we need to talk to it. And to talk to it, we must make a database connection. Logical, isn’t it?

Example

Here’s how we connect to a MySQL database on the localhost:

mysqlConnect.php

PHP Code:
<?php 
    $dsn 
'mysql:host=localhost;dbname=world;'
    
$user 'user';
    
$password 'secret'; try 

    
$dbh = new PDO($dsn$user$password); 

    catch (
PDOException $e)
{
    echo 
'Connection failed: ' $e->getMessage(); 

?>

We’d use this code to connect to a SQLite database on the localhost:

sqliteConnect.php

PHP Code:
<?php 
   $dsn 
'sqlite2:"C:\sqlite\world.db"'; try 

   
$dbh = new PDO($dsn);
 } 
   catch (
PDOException $e

   echo 
'Connection failed: ' $e->getMessage(); 
}
?>

Summary

Notice that in these two examples above, we simply create a new PDO object. Only the connection data for the PDO constructor differs in each case: for the SQLite connection, we need just the DSN; the MySQL connection also requires username and password arguments in order to connect to the database.
Support
Webnetics UK Ltd.
Reply


Messages In This Thread
POD vs mysql_function? - by webnetics - 29-02-08, 04:17 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)