查询不想显示表中所有相关的帖子

时间:2019-07-16 00:39:20

标签: php mysqli

我尝试检索与特定类别(大陆表)相关的所有行,但只显示一个而不是全部。

<?php

$townid = $_GET['id'];
$query = "SELECT * FROM towns INNER JOIN continents ON towns.catid = continents.id WHERE continents.id = '$townid'";

$row = mysqli_fetch_assoc(mysqli_query($link, $query));

// The category/Continent
echo '<h1>';
echo $row['catname'];
echo '</h1>';


//The post name/Town name
echo $row['title'];

?>

2 个答案:

答案 0 :(得分:0)

您需要循环调用mysqli_fetch_assoc()

$result = mysqli_query($link, $query);
$first = true;
while ($row = mysqli_fetch_assoc($result)) {
    if ($first) { // Only show the category header once.
        // The category/Continent
        echo '<h1>';
        echo $row['catname'];
        echo '</h1>';
        $first = false;
    }   

    //The post name/Town name
    echo $row['title'];
}

答案 1 :(得分:0)

您可以执行以下操作:

<?php
    $townid = $_GET['id'];
    $query = "SELECT * FROM towns INNER JOIN continents ON towns.catid = continents.id WHERE continents.id = '$townid'";

    $rows = mysqli_fetch_all(mysqli_query($link, $query), MYSQLI_ASSOC);

    // The category/Continent
    foreach ($rows as $row) {
        echo '<h1>';
        echo $row['catname'];
        echo '</h1>';

        //The post name/Town name
        echo $row['title'];
     }

 ?>

另一方面,最好从查询参数中获取参数,因为您是从GET参数中获取$townid的。 这是在PHP https://www.php.net/manual/en/mysqli-stmt.bind-param.php

中执行的操作