I coded a custom Database.class.php class that encapsulates a PDO object to interact with a MySQL database.
<?php
require_once('./classes/configs/Config.php');
class Database
{
private static $instance = null;
private function __construct()
{}
public static function getInstance()
{
if (self::$instance == null)
{
self::$instance = new PDO(
"mysql:host=".Config::DB_HOST.";dbname=".Config::DB_NAME."",
Config::DB_USER,
Config::DB_PWD);
return self::$instance;
}
}
}
?>
I've also coded a custom UserDAO.class.php which allows me for an easier way of performing CRUD operations.
For example, when I want to find a user in my database, I procede like so: $userdao->find('tim')
and store my
findings in a custom user.class.php object. (This class obviously calls a static Database.class.php object to use
the PDO object in that class).
Here is the find function in my UserDAO.class.php
public static function find($username)
{
$db = Database::getInstance();
$pstmt = $db->prepare("SELECT * FROM users WHERE username = :x");
$pstmt->execute(array(':x' => $username));
$result = $pstmt->fetch(PDO::FETCH_OBJ);
$p = new User();
if ($result)
{
$p->setUser_id($result->user_id);
$p->setUsername($result->username);
$p->setFirst_name($result->first_name);
$p->setLast_name($result->last_name);
$p->setEmail($result->email);
$p->setRegistration_date($result->registration_date);
$pstmt->closeCursor();
return $p;
}
$pstmt->closeCursor();
return null;
}
The problem is that I seem to be unable to use the $userdao
object more than once on a simple php page.
$userdao = new UserDAO();
$user5=$userdao->find('tim');
echo"<h3>".$user5."</h3>"; // this works fine (I have a toString function)
$user6=$userdao->find("john"); // this does not work....rest of the page is blank!!!!
echo"<h3>".$user6."</h3>";