MySQL SELECT语句只返回一行

时间:2012-03-18 09:15:37

标签: php mysql

我确信我的表中有两行数据符合where子句的条件,但我的编码只输出(回显)一行。我究竟做错了什么?

<?php


$connect= mysqli_connect("localhost", "root", "", "friends_list")
or die('error connecting with the database');

$query= "SELECT * FROM people WHERE age=19";

$result= mysqli_query($connect, $query)
or die('error querying the database');

$row= mysqli_fetch_array($result);

while ($row = mysqli_fetch_array($result))
{
echo $row['first_name'] . " " . $row['last_name'] . " is " . $row['age'] . "<br/>"                             
}
mysqli_close($connect);

?>

4 个答案:

答案 0 :(得分:5)

你吞咽了第一排,没有做任何事情;即改变:

$row= mysqli_fetch_array($result);

while ($row = mysqli_fetch_array($result))

为:

while ($row = mysqli_fetch_array($result))

答案 1 :(得分:0)

您正在获取第一行,但没有对其执行任何操作,因此不会在while循环内获取此行,因此不会输出。

$row= mysqli_fetch_array($result); // remove this

while ($row = mysqli_fetch_array($result))
{
echo $row['first_name'] . " " . $row['last_name'] . " is " . $row['age'] . "<br/>"                             
}

答案 2 :(得分:0)

在这部分:

$row= mysqli_fetch_array($result);

while ($row = mysqli_fetch_array($result))
{

你正在跳过第一行。你获取它,然后在while循环中你立即获取下一个。您应该删除第一次获取并仅使用:

while ($row = mysqli_fetch_array($result))
{

答案 3 :(得分:0)

<?php
    $connect= mysqli_connect("localhost", "root", "", "friends_list")
    or die('error connecting with the database');

    $query= "SELECT * FROM people WHERE age=19";

    $result= mysqli_query($connect, $query)
    or die('error querying the database');

    while ($row = $result->fetch_assoc()){
        echo $row['first_name'] . " " . $row['last_name'] . " is " . $row['age'] . "<br/>"                             
    }
    mysqli_close($connect);
?>

$result->fetch_assoc()将获取与sql条件匹配的所有内容,并且您可以像在上面那样避免进一步的错误。 您可以在这里fetch_assoc() function

了解更多信息