在非对象上调用成员函数exec()

时间:2012-12-14 18:43:00

标签: php pdo

<?php
$db = new PDO('mysql:host=localhost;dbname=dbname;charset=UTF-8', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
if(!ctype_digit($_GET['id']))
{
  echo 'A news ID is required to access this page. <a href="/index.php">Return</a>';
}
else
{
  $article = $sql = "SELECT `title`,`content`,`date` FROM `news` WHERE `id` = ?";

  $q = $db->prepare($article);
  $query->execute($article);

  return $query;
?>

致命错误:在第147行的/home/harold/public_html/news/index.php中的非对象上调用成员函数exec()

我绝对难过。我已经在这3天了。我不是最好的开发者,所以非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我不确定代码行147的哪一行,但似乎您在这些行中遇到问题:

$q = $db->prepare($article);
$query->execute($article);

首先,变量名称由于某种原因而改变。其次,您需要将您的ID作为数组发送给传递给execute()的参数(您再次传递查询)

它应该是这样的:

$stmt = $db->prepare($article);
$success = $stmt->execute(array($_GET['id']));

第三,当你甚至不在函数中时,你在这里使用return。我不确定你要做什么。

如果您想使用语句的结果集,则需要执行以下操作:

if ($success === false) {
    // the statement didn't execute for some reason
    var_dump($stmt->errorInfo());
} else {
    if ($stmt->rowCount() === 0) {
        // your select didn't return any rows
    } else {
        // I am assuming that you id field is unique, so that you will only return 1 row at most, so I am not using any sort of looping construct
        $news_object = $stmt->fetchObject();
        // alternately you can use this if you want an array -> $news_array = $stmt->fetch(); 
    }
}