fish man fish man - 5 months ago 44
MySQL Question

PHP explode string into pieces then insert into mysql

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++;
}

Answer
$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)."')");
}