Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting to PDO

Tags:

php

pdo

Many thanks for reading my post.

I am fairly new to PHP. I have been working on a project for a while now that uses mysqli and I am trying to convert it to using PDO. In my current set up I have a database class. But I have read on and off that when using PDO, its pointless or at least not necessary to have a database class when using PDO. I wanted to get some opinions on this. I know its a general question but I want to make sure that as I convert my site, I am proceeding in the right way.

Many thanks

Ok so here is the most basic example of my first stumbling block. Please try not to laugh too hard...look at this

  try {

  $handler = new PDO('mysql:host=localhost;dbname=app', 'root', 'fidelio');
  $handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    } catch(PDOException $e){

    echo $e->getMessage();
    die();
 }

  $name = "pdotest";
  $message = "Test message";
  $sql = "INSERT INTO guestbook (name, message, posted) VALUES (?, ?, NOW())";
  $query = $handler->prepare($sql);
  $query->execute(array($name, $message));

This works.

But why does this not work....

  class Database {


   private $handler;

    function Connect() {
    $db_host = "localhost";
    $db_name = "app";
    $db_user = "root";
    $db_pass = "fidelio";
    try {
        $this->handler = new PDO("mysql:host=" . $db_host . ";dbname=" . $db_name,  $db_user, $db_pass);
    } catch(PDOException $e) {
        die($e);
    }
}

}

database = new Database;
$name = "pdotest";
$message = "Test message";
$sql = "INSERT INTO guestbook (name, message, posted) VALUES (?, ?, NOW())";
$database->handler->prepare($sql);
database->execute(array($name, $message));
like image 330
GhostRider Avatar asked Feb 14 '26 08:02

GhostRider


1 Answers

Firstly $handler is private, you cannot access them directly

Secondly you forgot to use $database->Connect();

class Database {
  .....
  public function getHandler() {
    return $this->handler;
  }
}

$database = new Database;
$database->Connect();
$name = "pdotest";
$message = "Test message";
$sql = "INSERT INTO guestbook (name, message, posted) VALUES (?, ?, NOW())";

$database->getHandler()->prepare($sql);
$database->getHandler()->execute(array($name, $message));

note getHandler() function.

As "@Your Common Sense" said, note that Connect function should be called only once - so for this you can call this function in class constructor.

You can call Connect() function in class constructor __construct()

class Database {
  .....
   /**
    * Class constructor called when creating new object
    */
   public function __construct() {
       $this->Connect();
   }
}
like image 88
Павел Иванов Avatar answered Feb 16 '26 20:02

Павел Иванов



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!