Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
803 views
in Technique[技术] by (71.8m points)

php - Undefined variable: pdo, call to a member function prepare() on null

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...