1

知道为什么这显示为 null 的结果吗?我猜这与我在进行查询之前放置 $link 的位置有关,但必须这样做,对吗?

function getcatposts($cat_id) {
$qc = @mysqli_query($link, "SELECT * FROM topics WHERE topic_cat='$cat_id'");
while($row = mysqli_fetch_array($qc)) {
  $topic_title=$row['topic_subject'];
  $topic_id=$row['topic_id'];
}
$qc2 = @mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
  $cat_name=$row2['cat_name'];
}

更新代码:

function getcatposts($cat_id) {
$link = mysqli_connect("localhost", "lunar_lunar", "", "lunar_users");
$qc = mysqli_query($link, "SELECT * FROM topics WHERE topic_cat='$cat_id'");
while($row = mysqli_fetch_array($qc)) {
  $topic_title=$row['topic_subject'];
  $topic_id=$row['topic_id'];
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
  $cat_name=$row2['cat_name'];
}
echo $cat_name;
echo '<br />';
echo $topic_title;
echo '<br />';
echo $topic_id;
}

新问题是它的显示如下:http: //gyazo.com/43e8a91b9e0cf4f5e413536907891dcf.png 当数据库看起来像这样时:http: //gyazo.com/1ead8bd0f150838dae3ee4a476419679.png

它应该显示所有三个,这是一个函数,意味着它将继续重做所有代码,直到它无法查询更多数据。有任何想法吗?

4

2 回答 2

1

您的函数仅显示一个结果,因为您的 echo 在 while 循环之外...将 Echo 语句放入循环中,否则您将只打印最后一个结果!

while($row = mysqli_fetch_array($qc)) {
  $topic_title=$row['topic_subject'];
  $topic_id=$row['topic_id'];
  echo $topic_title;
  echo '<br />';
  echo $topic_id;
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
  $cat_name=$row2['cat_name'];
  echo $cat_name;
  echo '<br />';
}
于 2013-10-12T04:59:40.250 回答
1

这里的问题是您试图在循环之外回显这些值。循环内的变量将在每次迭代时被覆盖,在循环结束时,变量将保存最后一次迭代的值。

如果要显示所有值,请将echo语句移动到循环中,如下所示:

while($row = mysqli_fetch_array($qc)) 
{
    $topic_title = $row['topic_subject'];
    $topic_id = $row['topic_id'];
    echo $topic_title.'<br/>';
    echo $topic_id.'<br/>';
}

$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");

while($row2 = mysqli_fetch_array($qc2)) 
{
    $cat_name = $row2['cat_name'];
    echo $cat_name.'<br/>';
}

如果您关心顺序,可以将titles、ids 和cat_names 存储在数组中,如下所示:

while($row = mysqli_fetch_array($qc)) 
{
    $topic_title[] =$row['topic_subject'];
    $topic_id[] = $row['topic_id'];
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) 
{
    $cat_name[] =$row2['cat_name'];
}

然后遍历它们:

for ($i=0; $i < count($topic_id); $i++) { 
    if( isset($topic_id[$i], $topic_title[$i], $cat_name[$i]) )
    {
        echo $cat_name[$i].'<br/>';
        echo $topic_title[$i].'<br/>';
        echo $topic_id[$i].'<br/>';
    }
}
于 2013-10-12T05:02:08.713 回答