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

Categories

0 votes
805 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...