PHP将字符串分解成片段然后插入到mysql中

时间:2011-08-28 21:27:36

标签: php mysql insert explode

如何将explode字符串分成片然后插入mysql?

我想按句子插入每个单词,然后插入到mysql数据库中。但我不确定$str的长度是多少,可能是4个单词,也可能是10个单词。

那么如何制作一个foreach,将每个单词插入一个数据库(每行一行),谢谢。

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

4 个答案:

答案 0 :(得分:2)

非常简单,也不要使用addslashes(),我会使用mysql_escape_string()来解决与mysql相关的问题。

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

(当然,您可以再次添加更多条件,例如确保单词是唯一的等等。)

foreach()相当容易使用:

foreach($array as $value)

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

每次迭代都会更新$key$value

答案 1 :(得分: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)."')");
}

答案 2 :(得分: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."')";
}

答案 3 :(得分:1)

同样,如果您想减少运行的查询数量(这反过来会减少脚本运行所需的时间):

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

它基本上用')替换所有空格,('然后将整个事物包装成查询