1

即使有多个匹配条目(完全或部分匹配),我在下面的查询也只会显示一个结果。如何修复它,以便它返回所有匹配的条目:

//$allowed is a variable from database.

$sql = "SELECT `users`.`full_name`, `taglines`.`name`, `users`.`user_id` FROM 
`users`  LEFT JOIN `taglines` ON `users`.`user_id` = `taglines`.`person_id`
 WHERE ( `users`.`user_settings` = '$allowed' ) and ( `users`.`full_name` 
 LIKE '%$q%' ) LIMIT $startrow, 15";

$result = mysql_query($sql);

$query = mysql_query($sql) or die ("Error: ".mysql_error());

$num_rows1 = mysql_num_rows($result);

if ($result == "")
{
    echo "";
}
echo "";


$rows = mysql_num_rows($result);

if($rows == 0)
{

}
elseif($rows > 0)
{
    while($row = mysql_fetch_array($query))
    {
        $person = htmlspecialchars($row['full_name']);
    }
}
}  

print $person;
4

1 回答 1

2

$person因为您在每次迭代时都会覆盖。

$person[]如果您期望超过一个,请将其保存在一个数组中。然后在您打算输出时使用 foreach 循环遍历它。

不相关但您也查询两次,您只需要 1$result = mysql_query($sql);

更新(简单输出示例):

<?php 
$person=array();

while($row = mysql_fetch_array($query)){
 $person[] = array('full_name'=>$row['full_name'],
                   'email'=>$row['email'],
                   'somthing_else1'=>$row['some_other_column']);
}

//Then when you want to output:
foreach($person as $value){
    echo '<p>Name:'.htmlentities($value['full_name']).'</p>';
    echo '<p>Eamil:'.htmlentities($value['email']).'</p>';
    echo '<p>FooBar:'.htmlentities($value['somthing_else1']).'</p>';
}
?>

或者另一种方法是使用连接在循环内构建输出。

<?php 
$person='';
while($row = mysql_fetch_array($query)){
 $person .= '<p>Name:'.$row['full_name'].'</p>';
 $person .= '<p>Email:'.$row['email'].'</p>';
}

echo $person;
?>

或者只是回应它。

<?php 
while($row = mysql_fetch_array($query)){
 echo '<p>Name:'.$row['full_name'].'</p>';
 echo '<p>Email:'.$row['email'].'</p>';
}
?>
于 2012-05-03T23:54:13.453 回答