即使有多个匹配的条目(完全或部分匹配),我在下面的查询也只会显示一个结果。如何修复它以便返回所有匹配的条目:
//$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;
答案 0 :(得分: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>';
}
?>