php - 使用 foreach 分解字符串并插入多行太慢

标签 php mysql

我想用空格分解一个字符串,检查这个词是否已经存在。如果没有,将每一 block 插入 mysql 数据库中的多行。我以前试过这个...

<?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");
}
?>

这太慢了....

还有其他方法吗?

谢谢。

最佳答案

根据传递的内容,您可以SELECT 当前存在的单词,然后将它们留在INSERT 中。如果您的 word 列是一个键(我希望基于您的代码),另一个选项可能是 INSERT...ON DUPLICATE KEY。尝试以下操作:

<?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));
}
?>

关于php - 使用 foreach 分解字符串并插入多行太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10947760/

相关文章:

mysql - 用两个数据(外键)填充数据库字段

php - Laravel 4 Fluent Query Builder - stdClass 类的对象无法转换为字符串

MySQL 排序依据 - IN

php - 如何在 Windows 上启用 PHP HTTP PECL 扩展?

php - 在 PHP 中根据 USER ID 生成自己的页面

mysql - 将 Linux 命令转换为 Windows (mysql)

PHP登录系统

php - 在字符串中的美元符号后使用花括号是否错误

javascript - Codeigniter 中可扩展表内的表排序问题

php - Magento Rest api 通过电子邮件 ID 获取客户