提前道歉,因为我真的不确定如何提出这个问题,所以如果你需要知道任何事情,那么请评论而不是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"];
}
Run Code Online (Sandbox Code Playgroud)
这对我来说很容易理解.我一直试图用我所知道的转换它,事实证明我不太了解.到目前为止,我有以下内容:
$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();
Run Code Online (Sandbox Code Playgroud)
这会导致'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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
896 次 |
| 最近记录: |