为什么我收到PDO查询错误?

时间:2012-10-05 19:37:22

标签: php pdo

提前道歉,因为我真的不确定如何提出这个问题,所以如果你需要知道任何事情,那么请评论而不是downvote,我会编辑。

我的主页面上有预告片链接,点击后会打开一个包含完整文章的窗口。我目前正在将我的MySQL代码转换为PDO并且已经陷入困境。

在MySQL中,我曾经做过以下事情(这里,$ foo_query是第一页的查询):

$id = $_GET['id'];

$sql = "SELECT id, postdate, title, body FROM FooBarTable WHERE id = $id";
if ($foo_query = mysql_query($sql)) {
    $r     = mysql_fetch_assoc($foo_query);
    $title = $r["title"];
    $body  = $r["body"];
}

对我来说这很容易理解。我一直试图用我所知道的转换它,事实证明我不太了解。到目前为止,我有以下内容:

$id = $_GET['id'];

$sql = $DBH->prepare("SELECT id, postdate, title, body FROM FooBarTable WHERE id = :id OR id = $id");
$sql->bindParam(':id', $_REQUEST['id'], PDO::PARAM_INT);
if ($foo_query = $DBH->query($sql)) {
    $r->setFetchMode(PDO::FETCH_ASSOC);
    $r     = $foo_query->fetch();
    $title = $r["title"];
    $body  = $r["body"];
}
$sql->execute();

这会导致'PDO :: query()期望参数1为字符串'的错误。这是'if'行。

我是否已正确编写任何该PDO?从这里我需要做什么?一位朋友最近教我MySQL,但他根本不懂PDO,这意味着我不能问他的建议(并非所有有用的......)

4 个答案:

答案 0 :(得分:5)

这是正确的方法,注释:

try {
    //Connect to the database, store the connection as a PDO object into $db.
    $db = new PDO("mysql:host=localhost;dbname=database", "user", "password");

    //PDO will throw PDOExceptions on errors, this means you don't need to explicitely check for errors.
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //PDO will not emulate prepared statements. This solves some edge cases, and relives work from the PDO object.
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    //Prepare the statement.
    $statement = $db->prepare("SELECT id, postdate, title, body FROM FooBarTable WHERE id = :id");
    //Bind the Value, binding parameters should be used when the same query is run repeatedly with different parameters.
    $statement->bindValue(":id", $_GET['id'], PDO::PARAM_INT);
    //Execute the query
    $statement->execute();

    //Fetch all of the results.
    $result = $statement->fetchAll(PDO::FETCH_ASSOC);
    //$result now contains the entire resultset from the query.
}
//In the case an error occurs, a PDOException will be thrown. We catch it here.
catch (PDOException $e) {
    echo "An error has occurred: " . $e->getMessage();
}

答案 1 :(得分:2)

您需要使用PDOStatement::execute代替PDO::query

$foo_query = $sql->execute();

您也可以在致电execute时一次绑定所有参数:

$foo_query = $sql->execute(array(
    ':id' => $id
));

答案 2 :(得分:1)

您应将其更改为:

$sql->execute();
if($r = $sql->fetch()) {
    $title = $r["title"];
    $body = $r["body"];

答案 3 :(得分:1)

试试这个:

$sql = $DBH->prepare("SELECT id, postdate, title, body 
  FROM FooBarTable WHERE id = :id OR id = $id");
$sql->bindParam (':id', $_REQUEST['id'],PDO::PARAM_INT);
$sql->execute();

while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
  $title = $row["title"];
  $body = $row["body"];
}