我想用空格分解字符串,检查单词是否已存在。如果没有,请在mysql db中将每个部分插入多行。我以前试过这个......
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
include("connect.php");
$counter = 0;
$counters = 0;
$string = mysql_real_escape_string($_POST['words']);
$arr = explode(" ",$string);
foreach($arr as $str) {
$sql = mysql_query("SELECT * FROM unicode WHERE word = '$str'") or die (mysql_error());
if (mysql_num_rows($sql) == 0) {
$sqli = mysql_query("INSERT INTO unicode (word) VALUES ('$str')") or die (mysql_error());
$counters++;
} elseif (mysql_num_rows($sql) > 0) {
$counter++;
}
}
header("Location: ../addspellwords?success=457394056369&entered=$counters&duplicates=$counter");
}
?>
这太慢了......
还有其他办法吗?
感谢。
答案 0 :(得分:1)
根据传递的内容,您可以SELECT
找到当前存在的字词,然后将其留在INSERT
上。如果您的INSERT...ON DUPLICATE KEY
列是密钥(我希望根据您的代码),则另一个选项可能是word
。请尝试以下方法:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
include("connect.php");
$counter = 0;
$counters = 0;
$string = mysql_real_escape_string($_POST['words']);
$arr = explode(" ",$string);
$sql = mysql_query("SELECT `word` FROM unicode WHERE word IN ('".implode("', '", $arr) . ")") or die (mysql_error());
$dupes = array();
while($r = mysql_fetch_assoc($sql) {
$dupes[] = $r['word'];
}
$newwords = array_diff($arr, $dupes);
if(count($newwords)) {
$sqli = mysql_query("INSERT INTO unicode (word) VALUES ('" . implode("'),('", $newwords) . "')") or die (mysql_error());
}
header("Location: ../addspellwords?success=457394056369&entered=".count($newwords)."&duplicates=".count($dupes));
}
?>