Using mysql_connect() to connect to MySQL is easy, but it has many drawbacks. If your application uses another backend storage, you need to change the database function, for example, from mysql_connect pgsql_connect. A more important issue is it does not protect attacks from SQL Injection. These are the main reasons I started to explore PDO in my future PHP/MySQL projects.
I will rewrite my Generic Object with PDO later.
http://www.drupalschool.net/node/785
<?php
$database = new Database();
$db = $database->getDB();
$sql = 'select * from Users';
$stmt = $db->query($sql);
while ($user = $stmt->fetch(PDO::FETCH_OBJ)){
echo $user->Lastname.' '.$user->Student_id.'<br />';
}
// Connection data (server_address, database, username, password)
class Database {
private $host = 'myHost';
private $database = 'myDatabase';
private $user = 'myUser';
private $password = 'myPassword';
private $db ;
public function __construct() {
// Display message if successfully connect, otherwise retains and outputs the potential error
try {
$this->db = new PDO("mysql:host=$this->host; dbname=$this->database", $this->user, $this->password);
}
catch(PDOException $e) {
echo $e->getMessage();
}
} // constructor
public function getDB(){
return $this->db ;
}
} // class
?>