Call to a member function prepare() on null
I have searched every single answer regarding this and none seem to fully answer what's going on. Currently I am getting the error in the title when trying to prepare a statement with pdo.
I have tried:
Using a constructor instead
Using non-static
Using $this when I had a constructor
Catching PDO exceptions, none seem to be thrown
Here is main.php
class db {
public static $db;
public static $db2;
public static function start() {
$host = "localhost";
$dbname = "dbname";
$usr = "user";
$ps = "pass";
$pdo = "mysql:host=$host;dbname=$dbname";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => true
];
try {
db::$db = new PDO($pdo, $usr, $ps, $opt);
return db::$db;
} catch(PDOException $e) {
$e->getMessage();
}
}
}
And then to initialize the database, I call the start function in index.php with db::start();
Now, to the error.
Within main.php, in a whole different class and function, I try to call this connection statically.
$stmt0 = db::$db->prepare("SELECT * FROM users WHERE uname=:u");
But when done, I receive the error in the title, on this line.
Most would probably think, hmm, there must be an error with the connection then if it is calling it null. If that's the case, something is preventing my exception from being thrown because I see nothing in the error logs or on the page.
Your PDO is failing to connect, and since you aren't doing anything with that condition (you catch
it but then silently drop it), it's going under the radar.
Try removing the try..catch
block. If an error is happening in connection, you need to know!
我在http://phpfiddle.org/上试过这段代码,它工作正常:(打开URL,打开“CodeSpace”并粘贴下面的代码)
<?php
class db {
public static $db;
public static function start() {
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => true
];
try {
require "util/public_db_info.php";
$db = new PDO($dsn, $user_name, $pass_word);
return $db;
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
$db = db::start();
$result = $db->prepare("SELECT * FROM books WHERE id <= 10");
$status = $result->execute();
if (($status) && ($result->rowCount() > 0))
{
$results = array();
//convert query result into an associative array
while ($row = $result->fetch(PDO::FETCH_ASSOC))
{
$results[] = $row;
}
var_dump($results);
}
?>
链接地址: http://www.djcxy.com/p/69174.html
下一篇: 调用成员函数prepare()null