-2

I just tried a PDO wrapper from https://phpdelusions.net/pdo/pdo_wrapper.

First the PDO Wrapper

class MyPDO
{
    protected static $instance;
    protected $pdo;

    public function __construct() {
        $opt  = array(
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
            PDO::ATTR_EMULATE_PREPARES   => FALSE,
        );
        $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHAR;
        $this->pdo = new PDO($dsn, DB_USER, DB_PASS, $opt);

    }

    // a classical static method to make it universally available
    public static function instance()
    {
        if (self::$instance === null)
        {
            self::$instance = new self;
        }
        return self::$instance;
    }

    // a proxy to native PDO methods
    public function __call($method, $args)
    {
        return call_user_func_array(array($this->pdo, $method), $args);
    }

    // a helper function to run prepared statements smoothly
    public function run($sql, $args = [])
    {
        if (!$args)
        {
            return $this->query($sql);
        }
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($args);
        return $stmt;
    }
}

and then the user class

class User
{
    /* @var MyPDO */
    protected $db;

    protected $data;

    public function __construct()
    {
        $this->db = MyPDO::instance();
    }

    public function find($id)
    {
        $this->data = $this->db->run("SELECT * FROM user_account WHERE id = ?", [$id])->fetch();

    }
}

and then instantiate class user

$user = new User();
$a = $user->find(3);

var_dump($a);

There is a record associated with ID = 3 but the result I get is NULL, why?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Daksh B
  • 269
  • 1
  • 8
  • 45
  • 1
    We don't recommend software libraries here. Are any errors generated by your script? Did you check the connection? query? parameter? ...basic diagnostics. – mickmackusa Jan 30 '20 at 12:06
  • everything works fine and the null, I believe, is coming after the query has been executed. – Daksh B Jan 30 '20 at 12:12
  • 4
    the find method stores data into `$this->data` but nothing is returned. Try using a `var_dump` on `$this->data` in the find method and see what it outputs, it'll probably be your missing data. – Mark Jan 30 '20 at 12:15
  • If Mark's suggestion doesn't help, then https://stackoverflow.com/questions/16498640/pdo-prepare-with-question-marks-doesnt-work-with-numbers could be relevant, if I had to guess – ADyson Jan 30 '20 at 12:16

1 Answers1

3

As mentioned in the comments, the find method doesn't return anything, it is probably storing it just fine in $this->data but is never returned.

public function find($id)
{
    $this->data = $this->db->run("SELECT * FROM user_account WHERE id = ?", [$id])->fetch();
    return $this->data;
}
Mark
  • 1,852
  • 3
  • 18
  • 31