gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:38:31 24 4
gpt4 key购买 nike

提前致歉,因为我真的不确定如何提出这个问题,所以如果您需要了解任何信息,请发表评论而不是投反对票,我会进行编辑。

我的主页上有预告链接,单击该链接会打开一个包含完整文章的窗口。我目前正在将我的 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() expects parameter 1 to be string”。这是针对“if”行的。

我是否正确编写了任何 PDO?从这里我需要做什么?一位 friend 最近教我 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();
}

关于php - 为什么我会收到 PDO 查询错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12752950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com