gpt4 book ai didi

php - foreach中使用mysql请求时,先select好,后不select

转载 作者:太空宇宙 更新时间:2023-11-03 10:25:39 30 4
gpt4 key购买 nike

使用这段代码:

foreach ($content as $value) {
$data=$value[0];
echo $data;
$req="SELECT * FROM TABLE WHERE data='$data'";
$result=mysql_query($req) or die ('Erreur :'.mysql_error());
if (mysql_num_rows($result)){
echo ' ENTRY EXISTS';
}
else {
echo ' ENTRY DOES NOT EXIST';
}
}

对于第一个 $value,它找到了一个条目,这是正确的。对于下一个它没有,但它应该。如何解决?


更新代码

使用这段代码:

        $found_list = array();

$fetch_list = array();
foreach($content as $value){
$fetch_list[] = "'" . mysql_real_escape_string($value[0]) . "'";
}

if( empty($fetch_list) ){
echo '<p>No data to fetch</p>';
}else{

$sql = 'SELECT DISTINCT inst_name
FROM INSTITUTS
WHERE inst_name IN (' . implode(', ', $fetch_list) . ')';
$res = mysql_query($sql)
or die ('Error: ' . mysql_error());
while( $row = mysql_fetch_assoc($res) ){
$found_list[] = $row['inst_name'];
}
var_dump($found_list);
}

foreach($content as $value){
echo '<br/>';
echo $value[0] . ' ';
if( in_array($value[0], $found_list) ){
echo "ENTRY EXISTS\n <br/>";
}else{
echo "ENTRY DOES NOT EXIST\n <br/>";
}
}

结果是:

 array(3) { [0]=> string(13) "AixEnProvence" [1]=> string(19) "AixEnProvenceAnnexe" [2]=> string(7) "Acheres" } 
acheres ENTRY DOES NOT EXIST
AixEnProvence ENTRY EXISTS
aixenprovenceannexe ENTRY DOES NOT EXIST
instituttest ENTRY DOES NOT EXIST

最佳答案

没有理由用几乎相同的查询来淹没 MySQL 服务器。看看 IN expression :

SELECT foo, bar
FROM table
WHERE data IN ('a', 'b', 'c');

我还建议您使用 google 搜索 SQL 注入(inject)和 XSS 攻击。

编辑:这里有一些代码可以解决最新评论中描述的问题:

<?php

// $content = ...
$found_list = array();

$fetch_list = array();
foreach($content as $value){
$fetch_list[] = "'" . mysql_real_escape_string($value[0]) . "'";
}

if( empty($fetch_list) ){
echo '<p>No data to fetch</p>';
}else{
$sql = 'SELECT DISTINCT data
FROM table
WHERE data IN (' . implode(', ', $fetch_list) . ')';
$res = mysql_query($sql)
or die ('Error: ' . mysql_error());
while( $row = mysql_fetch_assoc($res) ){
$found_list[] = $row['data'];
}
}

foreach($content as $value){
echo $value[0] . ' ';
if( in_array($value[0], $found_list) ){
echo "ENTRY EXISTS\n";
}else{
echo "ENTRY DOES NOT EXIST\n";
}
}

?>

更新问题的答案:

PHP comparison operators区分大小写:

<?php
var_dump('Acheres'=='acheres'); // bool(false)
?>

您可以使用 strtolower()在比较之前对值进行归一化。

关于php - foreach中使用mysql请求时,先select好,后不select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5938548/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com