phpmysql

php - Explode string and insert into multiple rows with foreach is too slow


I want to explode a string with a space, check whether the word already exists. If not, insert each piece into multiple rows in mysql db. I've tried this before...

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

This is too too too much slow....

Is there any other way to do this?

Thanks.


Solution

  • Based on what's passed you can go SELECT the words that currently exist, then leave those out on the INSERT. Another option may be INSERT...ON DUPLICATE KEY if your word column is a key (which I hope based on your code). Try the following:

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