1

我想用空格分解一个字符串,检查这个词是否已经存在。如果没有,请将每个片段插入 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");
}
?>

这也太慢了。。。。

有没有其他方法可以做到这一点?

谢谢。

4

1 回答 1

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));
}
?>
于 2012-06-08T11:30:18.307 回答