I instantiated a PDO object instead of a mysqli object in my database class. Obviously my mysqli functions no longer work. How do I update this line.
$row=mysqli_fetch_row(database::query($query));
one_db::$db holds the pdo resource…query is just…
public function query($query)
{
return one_db::$db->query($query);
}
Actually I’m not sure if this needs updating as well to work with PDO…
Here is my PDO instantiation, I left in the mysqli for comparison
private function __construct()
{
self::create_pdo_object();
}
private function create_pdo_object()
{
try {
self::$db = new PDO(DB_DRIVER, DB_USER, DB_PASS);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
private function create_mysqli_object()
{
self::$db=new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
}
It looks like you might ought to consider using the factory pattern. Unfortunately, in your case, I don’t want to rewrite your entire class so we’re gonna use a modified factory pattern. Create a function named factory() like so:
Incidentally, if you’re going to use
selfthen your functions should be declaredstatic. In which case, it’s considered best practice to prefix them with underscores. And if you’re gonna go that route, then you might as well follow the convention for camel casing function names. (although, it could be argued that those functions should be public in case you don’t want to use factory, in which case you should omit the underscore prefix).Also, your
__construct()function should have thepublicaccess modifier. You could callfactory()from within your constructor, but they are static methods using a static class member (self::$db), so instantiating an object is kind of pointless. Nevertheless, here is the code:As far as fetching a row with PDO, you would need to alter the code to something like:
If this code exists in your db class, then you would change
$dbtoself::$db, but I’m not sure where you would want to put that code..For more information on querying using PDO, check out this page.