Salih K Salih K - 1 month ago 8
PHP Question

Getting Error while using PDO: Fatal error: Call to a member function prepare() on null

I am learning PDO, and I am keep getting this error, I did some searches and nothing resolves the issue. Here is the code I am Using:

index.php:::

require_once 'database/Connection.php';
require 'Task.php';
$pdo = Connection::make();

$statement = $pdo->prepare("select * from todos");
$statement->execute();
$tasks= $statement->fetchAll(PDO::FETCH_CLASS, 'Task');

<ul>
<?php foreach ($tasks as $task) : ?>
<li><?= $task->description; ?></li>
<?php endforeach; ?>
</ul>


Connection.php:::

class Connection {

public static function make() {
try {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', 'mysql');
} catch(PDOException $e) {
die($e->getMessage().' DB Could not find');
}
}

}

Answer

Use return keyword as:

class Connection {

    public static function make() {
        try {
                return $pdo = new PDO('mysql:host=127.0.0.1;dbname=mytodo', 'root', 'mysql');
            } catch(PDOException $e) {
                die($e->getMessage().' DB Could not find');
            }
    }

}

Comments