1

How to explode string into pieces then insert into mysql?

I want to insert every word by the sentence, then insert into mysql database. But I am not sure what is the length of the $str, it may be 4 words, also can be 10 words.

So how to make a foreach, insert each word into a database (each word in one line), Thanks.

$str = "This is a test";
$piece = explode(' ',$str);
$num=0;
for(){
...
mysql_query("INSERT INTO test (words) SELECT '".addslashes($piece[$num])."' FROM dual WHERE not exists (SELECT words FROM test WHERE test.words = '".addslashes($piece[$num])."')");
$num++; 
}
2
  • 1
    If your installation supports it, you might want to use PDO and then you can create the query and simply update your params for each iteration. Commented Aug 28, 2011 at 21:47
  • I have PDO, but I have never studied it. Thanks. Commented Aug 28, 2011 at 21:58

4 Answers 4

2

Pretty easy, also don't use addslashes(), I'd use mysql_escape_string() for everything mysql related.

$str = "This is a test"; 
$pieces = explode(' ', $str);
foreach($pieces as $piece)
    mysql_query('insert into test (words) values (\'' . $piece . '\');');

(Of course you can add more conditions again, e.g. ensure words are unique, etc.)

foreach() is rather easy to use:

foreach($array as $value)

or

foreach($array as $key => $value)

where $key and $value are updated each iteration.

Sign up to request clarification or add additional context in comments.

Comments

1
$str = "This is a test";
$piece = explode(' ',$str);
foreach($piece as $substr){
    mysql_query("INSERT INTO test (words) SELECT '".mysql_real_escape_string($substr)."' FROM dual WHERE not exists (SELECT words FROM test WHERE test.words = '".mysql_real_escape_string($substr)."')");
}

Comments

1

$str = "This is a test";

// make sure there are only letters and spaces in your text (prevents
// something like "demo," in your database
$str = preg_replace("/[^a-zA-Z0-9\ ]/", " ",$str);

// explode it
$words = explode(' ',$str);

// make sure we have unique words
$words = array_unique($words);

foreach ($words as $word) {
    mysql_query("INSERT INTO test (word) values ('".$word."')";
}

Comments

1

Similarly, if you want to decrease the number of queries you run (which, in turn, will decrease the amount of time your script takes to run):

<?php
$str="This is a test";
$words=explode(' ',mysql_escape_string($str));
$query="insert into test (words) values ('".implode("'),('",array_unique($words))."')";
$result=mysql_query($query);
?>

It essentially replaces all spaces with '),(' and then wraps the whole thing into a query

Comments

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.