怎么回声整个表?现在我只得到最后一排

时间:2013-12-05 11:59:19

标签: php mysql

我现在有了这个代码而且我只获得了最后两行,但是我需要使用html获得与数据库中一样多的代码。提前谢谢

      //We include the includes.php, which contains our db connection data.
       include("includes.php"); 
       //dbCon(); references the db connection data in includes.php - in other words we call a function.
     dbCon();
     $query = "SELECT * FROM product WHERE categoryid = 1;";
    $result = mysqli_query($dbc,$query) or die('Error querying database.');
      if (mysqli_num_rows($result) == NULL) {
     mysqli_close($dbc);header("Location:index.php?l=f");exit();
      }

    while ($row = mysqli_fetch_assoc($result)){
       $name = $row['name'];
        $price = $row['price'];
}

    echo "<input type='checkbox' name='name' value='name'>".$name."</br>";
    echo "Price: "." "."<strong>".$price."</strong></br>";

3 个答案:

答案 0 :(得分:1)

将回声移动到循环内

while ($row = mysqli_fetch_assoc($result)){
    $name = $row['name'];
    $price = $row['price'];
    echo "<input type='checkbox' name='name' value='name'>".$name."</br>";
    echo "Price: "." "."<strong>".$price."</strong></br>";

    }

答案 1 :(得分:0)

你的回声代码必须在循环内。您编辑的代码必须如下:

//We include the includes.php, which contains our db connection data.
    include("includes.php"); 
    //dbCon(); references the db connection data in includes.php - in other words we call a function.
    dbCon();
    $query = "SELECT * FROM product WHERE categoryid = 1;";
    $result = mysqli_query($dbc,$query) or die('Error querying database.');
    if (mysqli_num_rows($result) == NULL) {
    mysqli_close($dbc);header("Location:index.php?l=f");exit();
    }

    while ($row = mysqli_fetch_assoc($result)){
    $name = $row['name'];
    $price = $row['price'];
    echo "<input type='checkbox' name='name' value='name'>".$name."</br>";
    echo "Price: "." "."<strong>".$price."</strong></br>";
    }

答案 2 :(得分:0)

问题是你在每个循环中覆盖$ name和$ price变量。因此,在while循环结束时,您将把数据存储在最后一行的变量中。

解决方案是在每个循环中回显它们,或者在变量中收集每次迭代的输出,然后在结尾处打印一次。

$output = '';
while ($row = mysqli_fetch_assoc($result)){
        $name = $row['name'];
        $price = $row['price'];
        $output .= "<input type='checkbox' name='name' value='name'>".$name."</br>";
        $output .= "Price: <strong>".$price."</strong></br>";  
}
echo $output;

或者简单地说:

while ($row = mysqli_fetch_assoc($result)){
        $name = $row['name'];
        $price = $row['price'];
        echo"<input type='checkbox' name='name' value='name'>".$name."</br>";
        echo "Price: <strong>".$price."</strong></br>";  
}