PHP将字符串分解成碎片然后插入到mysql中
如何将字符串分解成碎片然后插入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++;
}
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++;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
非常简单,也不要使用
addslashes()
,我会使用mysql_escape_string()
来处理与 mysql 相关的所有内容。(当然你可以再次添加更多条件,例如确保单词唯一等)
foreach()
相当容易使用:or
where
$key
and$value
每次迭代都会更新。Pretty easy, also don't use
addslashes()
, I'd usemysql_escape_string()
for everything mysql related.(Of course you can add more conditions again, e.g. ensure words are unique, etc.)
foreach()
is rather easy to use:or
where
$key
and$value
are updated each iteration.同样,如果您想减少运行的查询数量(这反过来会减少脚本运行所需的时间):
它本质上用 '),(' 替换所有空格,然后将整个内容包装到一个查询
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):
It essentially replaces all spaces with '),(' and then wraps the whole thing into a query