将URL参数传递给Mysql查询

时间:2015-02-12 20:40:09

标签: php html mysql

希望我能得到一些帮助。

我有一个controller.php,用于查询数据库以显示已添加的最近文章的列表。

try    
{
  $recents = $pdo->query('SELECT id, blogtitle FROM article ORDER BY id DESC LIMIT 0,6');
}

catch (PDOException $e)
{
  $error = 'Error fetching blog posts: ' . $e->getMessage();
  include 'error.html.php';
  exit();
}

在同一个控制器中,我然后遍历数据并存储在一个数组中:

foreach ($recents as $recent)
{
    $newest[] =  array ('id' => $recent['id'], 'blogtitle' =>  $recent['blogtitle']);
}

同一个controller.php加载了一个article.html.php,它将最近项目列表显示为超链接:

<section id="secondary">
    <h2 class="recent">Recent Posts</h2>
    <?php foreach ($newest as $new):?>
    <a href="article-detail.php?id=<?php echo htmlout($new['id']);?>"><?php echo htmlout($new['blogtitle']) . "</a>";?>
    <?php endforeach; ?>
</section>

正如您所看到的,我已将文章ID附加到网址,以便它可以被拾取并用于为特定博客文章生成mysql查询。

我再次决定使用相同的controller.php来加载文章详细信息页面,其中包含与网址中传递的ID相关的特定文章。

所以controller.php会检查url中的id是否为isset,如果是,则将该id传递给mysql查询以将相关文章检索到id:

if (isset($_GET['id']))
{
        include 'article-detail.php';
        exit();

        include  'dbinc/db.inc.php';
        include  'includes/magic.inc.php';

        try 
        {
            $sql = 'SELECT article.id, article.blogdate, article.blogtitle, article.blogtext, author.name 
            FROM article INNER JOIN author
            ON authorid = author.id
            WHERE article.id = :id';
            $s = $pdo->prepare($sql);
            $s->bindValue(':id', $_GET['id']);
            $s->execute();
        }
         catch (PDOException $e)
        {
          $error = 'Error fetching blog posts: ' . $e->getMessage();
          include 'error.html.php';
          exit();
        }

    while ($row = $s->fetch(PDO::FETCH_ASSOC))
    {
         $blogdate = $row['blogdate'];
         $blogtitle = $row['blogtitle'];
         $blogtext = $row['blogtext'];
         $authorname = $row['name'];
    }

}

然后article-detail.php使用$ blogdate,title,text等来显示具有标准html的特定文章。所以你可以看到我试图在这里坚持一个控制器/模板模型。

但是,当我点击任何超链接时,通过这个过程,ID肯定会在URL中传递,但我不认为控制器正在正确地获取id,因此不传递id到mysql查询来检索特定的文章?

基本上,当我单击其中一篇文章链接时,详细信息页面会加载,但$ blogdate,$ blogtext等未定义,因为我不认为id正确传递给mysql查询?

所以,对于我出错的地方有任何帮助或建议。

干杯

0 个答案:

没有答案