$hostname = 'localhost';
$username = 'uname';
$password = 'password';
$dbName = 'events';
if (class_exists('PDO')){
echo("PDO Exists");
}
else {
echo("PDO Does Not Exist");
}
try {
$pdo = new PDO("mysql:host=$hostname;dbname=$dbName", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
$error = $e->getMessage();
die($error);
}
$stmt = $pdo->prepare('SELECT * FROM event');
$stmt->execute();
$events = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($events);
输出
PDO Exists
Fatal error: Call to a member function prepare() on a non-object in /home/blah/getEvents.php on line 25
答案 0 :(得分:0)
这是因为$pdo
对象未在该范围内定义。移动
$stmt = $pdo->prepare('SELECT * FROM event');
变量后,在 $pdo
到try语句。
为了执行该查询,您需要调用execute方法:
$stmt->execute();
要对此进行调试,您需要执行var_dump($pdo)
以查看其中包含的内容。
答案 1 :(得分:0)
可能没有抛出异常。启用这样的例外:
try {
$pdo = new PDO("mysql:host=$hostname;dbname=$dbName", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}