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 c开发者_如何学运维an 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++;
}
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.
$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)."')");
}
$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."')";
}
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
精彩评论