Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was following a video and double checking all code and everything seems to be the same yet I get these errors.

Errors:

Notice: Undefined variable: pdo in QueryBuilder.php on line 14

Fatal error: Call to a member function prepare() on null in QueryBuilder.php on line 14

QueryBuilder.php:

class QueryBuilder
{
    protected $pdo;

    public function __construct($pdo)
    {
        $this->pdo = $pdo;
    }

    public function selectAll($table)
    {
        $query = $pdo->prepare("SELECT * FROM `$table`"); // --> LINE 14 <--
        $query->execute();
        return $query->fetchAll();
    }
}

Connection.php:

class Connection
{
    public static function make()
    {
        $servername = "localhost";
        $dbUsername = "root";
        $dbPassword = "";
        $dbName = "test";

        try {
            $pdo = new PDO("mysql:host=$servername;dbname=$dbName", $dbUsername, $dbPassword);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            return $pdo;
        }
        catch(PDOException $e){
            die($e->getMessage());
        }
    }
}

init.php:

require "database/Connection.php";
require "database/QueryBuilder.php";
require "app/Product.php";

$query = new QueryBuilder(Connection::make());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
781 views
Welcome To Ask or Share your Answers For Others

1 Answer

As stated in comments, in OOP, you need to use $this->pdo passing the object's property for it, instead of the variable $query = $pdo-> since you've construct'ed it in:

public function __construct($pdo)
{
    $this->pdo = $pdo;
    ^^^^^^^^^^
}

I.e.:

$query = $this->pdo->prepare

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...