我编写了一个脚本,用于检查通过文本区域接收的名称的批量输入,并忽略数据库中已有的所有值。如果您只输入一个重复的名称,它就会起作用。如果输入两个或多个,它将过滤掉第一个重复的名称,将其余的视为唯一名称并将它们插入数据库中。我不明白为什么。
首先,这是一个在脚本的另一部分中构建的数组。它是从数据库查询生成的:
Array
(
[0] => john
[1] => peter
[2] => max
[3] => jake
)
该数组称为 $onlyHandles。那么这是脚本:
if((isset($_POST['extract']) && !empty($_POST['extract']))){
$handles = trim($_POST['extract']);
$handles = explode("\n", $handles);
if(count($handles)>200){
echo 'error';
exit(1);
}
foreach($handles as $handle) {
$handleRep = strtolower(str_replace('@','',$handle));
$handleClean = str_replace(str_split('\\/:*?&"<>=+-#%$|'), ' ', $handleRep, $count);
if ($count > 0) {
echo 'error';
exit(1);
}
else{
if (in_array($handleClean, $onlyHandles)){
$delmessage .= "<p>".$handleClean." is already in your list.</p>";
}
else{
$sqlIns = "INSERT INTO...blah blah blah)";
$resultIns = mysql_query($sqlIns);
$resInsArr[] = array($resultIns);
}
}
}
$countresIns = count($resInsArr);
if ($countresIns > 0){
$delmessage .= "<p>User(s) added to list succesfully!</p>" ;
}
}
现在,如果您在文本区域中输入“john”,它会大喊该名称已存在。如果您输入“john”和“max”,它将省略 john 并添加 max。
任何帮助将不胜感激。
附注关于查询格式,我知道了,我知道了,谢谢!
最佳答案
我想给你一些关于如何实现它的想法:
替换第一行:
if((isset($_POST['extract']) && !empty($_POST['extract']))){
通过
if((!empty($_POST['extract']))){
因为!empty
已经给你保证了 isset
- 我怀疑游戏中存在一些特殊字符
您还可以使用正则表达式的强大功能来替换不需要的字符 替换中:
第 12 行:$handleClean = str_replace(str_split('\\/:*?&"<>=+-#%$|'), ' ', $handleRep, $count);
通过:
$handleClean = preg_replace("/\[\/:\*?&\"<>=\+-#%\$\|\]*/", ' ', $handleRep, $count);
- 在 Ur For-Loop 中,重构以下几行怎么样:
第 2 行:$handles = trim($_POST['extract']);
穿过(不需要修剪)
$handles = $_POST['extract'];
并且
第 11 行:$handleRep = strtolower(str_replace('@','',$handle));
通过
$handleRep = trim(strtolower(str_replace('@','',$handle)));
嘿;-),
你还应该添加一些 print_r(...) 来调试每个步骤
关于PHP foreach 循环搞乱了我的 in_array 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35021852/