【问题标题】:How to set a parameter in a link?如何在链接中设置参数?
【发布时间】:2014-12-24 13:44:34
【问题描述】:

我从我的数据库中查询我正在处理的一个论坛。出于某种原因,我无法让 id 显示在链接中。我一直在绞尽脑汁想弄清楚。它适用于我的所有其他页面,除了这个。这是我正在使用的代码:

$topicsql = "SELECT topic_id,topic_subject,topic_date,topic_cat FROM topics
            WHERE topic_cat = " . $row['cat_id'] . "
            ORDER BY topic_date DESC LIMIT 1";

$topicsresult = mysqli_query($con, $topicsql);

if(!$topicsresult)
{
    echo 'Last topic could not be displayed.';
}
else
{
    if(mysqli_num_rows($topicsresult) == 0)
    {
        echo 'no topics yet';
    }
    else
    {

        while($topicrow = mysqli_fetch_assoc($topicsresult))
        //Limit the number of characters in the latest topic link
        $subject=   substr($topicrow['topic_subject'], 0, 25);
        $topic=$topicrow['id'];


        echo '<a href="topic.php?id=' . $topicrow['topic_id'] . '">' . $subject . '&hellip;</a><br> on ' . date('m-d-Y', strtotime($topicrow['topic_date']));
 }
}

当您将鼠标悬停在链接上时,我只会看到 topic.php?id=,但我应该会看到 topic.php?id=24

【问题讨论】:

  • 请提及您在悬停时看到的内容。
  • 当我将鼠标悬停在链接上时,我会看到 topic.php?id=......我应该看到 topic.php?id=24
  • 请检查topic_id是否在topicrow中;很可能你在弄乱名字。

标签: php database mysqli hyperlink


【解决方案1】:

试试这个方法:

   $query = "SELECT topic_id,topic_subject,topic_date,topic_cat FROM topics
              WHERE topic_cat = ?
              ORDER BY topic_date DESC LIMIT 1";
    if ($stmt = mysqli_prepare($con, $query)) {   
        mysqli_stmt_bind_param($stmt,'i', $row['cat_id']);
        /* execute prepared statement */
        mysqli_stmt_execute($stmt);   
        /*bind the result*/
        $stmt->store_result();
        /*Count the rows*/
        if( mysqli_stmt_num_rows($stmt) > 0){
            while($row = mysqli_fetch_assoc($stmt)){
                /*Limit the number of characters in the latest topic link*/
                $link = '<a href="topic.php?id=' . $row['topic_id'] . '">';
                $link .= substr($row['topic_subject'], 0, 25) . '&hellip;</a><br>';
                $link .= 'on '.date('m-d-Y', strtotime($row['topic_date']));
                echo $link;
            }
        }else{
            echo 'Last topic could not be displayed.';
        }   
        /* close statement */
        mysqli_stmt_close($stmt);
    }else{
        printf("Errormessage: %s\n", mysqli_error($con));
    }

由于它正在创建链接,这意味着您的查询找到了行,如果您看到 id 为空白,则表明列名不匹配。

此时只有你知道,我的建议是像上面那样重写代码,我只是想指出prepared statement,命名变量,减少变量数量,缩进,吃你的蔬菜的最佳实践...... . 所有这些都将帮助您避免像代码中令人困惑的部分这样的错误:

首先是您的查询:

SELECT topic_id ...

那么当你检索到时:

$topic=$topicrow['id'];

打印查询:

echo '<a href="topic.php?id=' . $topicrow['topic_id'] 

因此请仔细阅读您的代码并注意细节。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    相关资源
    最近更新 更多