簡體   English   中英

為什么我收到PDO查詢錯誤?

[英]Why am I receiving a PDO query error?

提前道歉,因為我真的不確定如何提出這個問題,所以如果你需要知道任何事情,那么請評論而不是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,這意味着我不能問他的建議(並非所有有用的......)

這是正確的方法,有評論:

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();
}

您需要使用PDOStatement::execute而不是PDO::query

$foo_query = $sql->execute();

調用execute時,您也可以一次綁定所有參數:

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

您應該將其更改為:

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

嘗試這個:

$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"];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM