2

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

我的主页上有预告链接,点击后会打开一个包含完整文章的窗口。我目前正在将我的 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

4 回答 4

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();
}
于 2012-10-05T19:50:59.347 回答
2

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

$foo_query = $sql->execute();

您也可以在调用时一次绑定所有参数execute

$foo_query = $sql->execute(array(
    ':id' => $id
));
于 2012-10-05T19:40:39.687 回答
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"];
}
于 2012-10-05T19:45:42.887 回答
1

您应该将其更改为:

$sql->execute();
if($r = $sql->fetch()) {
    $title = $r["title"];
    $body = $r["body"];
于 2012-10-05T19:41:13.063 回答