为什么这个查询只显示一个结果? [英] Why does this query only show one result?

查看:39
本文介绍了为什么这个查询只显示一个结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的查询将使用搜索脚本.出于某种原因,它不会返回任一条件为真的所有结果.我做错了什么?

The query below will be used a search script. For some reason it won't return all results where either condition is true. What am i doing wrong?

$sql = "SELECT name, id_code from codes WHERE name LIKE '%$q%' OR id_code 
LIKE '%$q%'";

$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)
{
print("<div id=norequests>No results for <strong>$q</strong></div>");

}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{

$name = htmlspecialchars($row['name']);
$code = htmlspecialchars($row['id_code']);

}

print("$code: $name<br /> <br />");
}

}


else{
    echo '<div id="error">No results for $q.</div>';
}

推荐答案

您正在 while 之外打印.这意味着,无论您有多少结果,都只会打印一个.

You are printing outside of while. Which means, no matter how many results you have, only the one will be printed.

要么在循环内打印

while($row = mysql_fetch_array($query))
{
    $name = htmlspecialchars($row['name']);
    $code = htmlspecialchars($row['id_code']);
    print("$code: $name<br /> <br />");
}

或者在循环时收集数组中的变量并在循环后随意使用它们

or collect the variables in an array while looping and use them after the loop as you like

$result_array = array();
while($row = mysql_fetch_array($query))
{
    $name = htmlspecialchars($row['name']);
    $code = htmlspecialchars($row['id_code']);

    $result_array[] = array(
        'name' => $name,
        'code' => $code
    );
}
print_r($result_array);

这篇关于为什么这个查询只显示一个结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆