1

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.

4
  • Can the word column in table unicode be unique? Commented Jun 8, 2012 at 11:16
  • You have an extra } at the end. Is it intended? Commented Jun 8, 2012 at 11:28
  • this is end of the server request @PraveenKumar Commented Jun 8, 2012 at 11:30
  • Okay, I got it now. Sorry, my mistake! :) Commented Jun 8, 2012 at 11:31

1 Answer 1

1

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));
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

You could even improve it slightly by using array_unique() on the $arr array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.