PDO获得价值

时间:2012-03-08 00:30:26

标签: php pdo

我做了一个博客。除了一件事,一切都正常;能够比较我的id以打开相应的文章。

我正在使用FETCH_ASSOC

$sth->setFetchMode(PDO::FETCH_ASSOC); 

我正在$_GET检查id

if (isset($_GET['id']) && ($_GET['id'] == $blogid['id'])) { **PROBLEM IS WITH $blogid
$row = $sth->fetch()
//... Code to display html and db values 

如果为true,则会显示整篇博文。否则它会显示所有博客介绍:

<?php } else { ?>
<?php while($row = $sth->fetch()) {  ?>
//... Code to display html and db values

如何在我的id声明中访问if?如果我这样做:

$blogid = $sth->fetch()

通过重新排序帖子

来搞砸$row = $sth->fetch()

编辑查询添加:

$sth = $dbh->query('SELECT id, title, slug, body, image, author, date, category from blog ORDER BY date DESC');

1 个答案:

答案 0 :(得分:3)

你在这里使用PDO和MySQL略有错误。而不是获取所有博客文章并检查您所拥有的博客是否具有正确的ID,您应该只使用WHERE从数据库中获取一个博客帖子(行)条款,像这样:

SELECT id, title, ... FROM blog 
WHERE id=[ID from $_GET] 
ORDER BY date DESC

PDO通过允许您使用占位符来非常好地处理这个问题:

SELECT id, title, ... FROM blog 
WHERE id=:theBlogID 
ORDER BY date DESC

在这里,我使用了占位符:theBlogID,它将被$_GET参数替换。

使用PDO,您的最终代码需要准备查询,将参数绑定到它,执行它然后获取结果(检查是否确实存在使用PDO::rowCount()的结果)这样的事情:

$sth = $dbh->prepare('SELECT id, title, ... FROM blog 
                      WHERE id=:theBlogID 
                      ORDER BY date DESC');

$sth->bindParam(':theBlogID', $_GET['id'], PDO::PARAM_INT);    // Bind the ID from $_GET to the placeholder

$result = $sth->execute();    // Execute (run) the query

if($result->rowCount()) {    // Have we found any blog posts with the ID specified?
    $data = $result->fetchAll();

    foreach($data as $post) {
        // Print out your blog post
    }
}

目前尚不清楚您目前有多少以上,因为您只在这里和那里提供一两个线条片段,但这应该可以很好地概述您需要做什么。