将代码更改为以下内容:
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) {
echo $quan." ".$row['name']. "\n";
}
}
}
您必须遍历结果。顺便说一句,停止使用mysql_query()
!请改用 MySQLi 或 PDO(并注意SQL 注入;您可以使用它mysqli_real_escape_string()
来处理输入参数)。对于 MySQLi 实现,这里是:
foreach ($arr as $name => $quan) {
$query = "SELECT * FROM table WHERE name='$name'";
$result = mysqli_query($query) or die(mysqli_error());
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
echo $quan." ".$row['name']. PHP_EOL;
}
}
}
相反"\n"
,我更喜欢使用PHP_EOL
(如上所示)
正如评论所暗示的,SQL 语句可以执行一次,如下所示:
$flipped_array = array_flip($arr); // flip the array to make "name" as values"
for($i = 0; $i < count($flipped_array); $i++) {
$flipped_array[$i] = '\'' . $flipped_array[$i] . '\''; // add surrounding single quotes
}
$name_list = implode(',', $arr);
$query = "SELECT * FROM table WHERE name IN ($name_list)";
// ... omit the followings
例如,在 $arr 中包含“peter”、“mary”、“ken”,查询将是:
SELECT * FROM table WHERE name IN ('peter','mary','ken')
旁注:但我不明白你的查询。您只从查询中获取名称?您可以检查行数,甚至可以按名称分组,例如:
SELECT name, COUNT(*) AS cnt FROM table GROUP BY name ORDER BY name
得到你想要的。
更新(再次):根据 OP 的评论,这里是解决方案:
$flipped_array = array_flip($arr); // flip the array to make "name" as values"
for($i = 0; $i < count($flipped_array); $i++) {
$flipped_array[$i] = '\'' . $flipped_array[$i] . '\''; // add surrounding single quotes
}
$name_list = implode(',', $arr);
$query = "SELECT name, COUNT(*) AS cnt FROM table WHERE name IN ($name_list) GROUP BY name HAVING COUNT(*) > 0 ORDER BY name";
$result = mysqli_query($query) or die(mysqli_error());
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
echo $quan." ".$row['name']. ": " . $row['cnt'] . PHP_EOL;
}
}
上面的查询将只显示出现在表中的名称。不在表中的名称将不会显示。现在完整的代码(再次小心 SQL 注入)