I want to put all words of a string in different rows of a table in mysql. for example.
$mystring="this is an ugly string"
i want to put in mysql table like
id word
1 this
2 is
3 an
4 ugly
5 string
i think first i have to use explode function then use for each loop, but im not able to write the correct sytax, can someone help me with the syntax please ?
Thanks
breaking string and putting mysql.
Started by Macintosh, Mar 19 2007 06:35 AM
3 replies to this topic
#1
Posted 19 March 2007 - 06:35 AM
#2
Posted 19 March 2007 - 07:33 AM
Try this...
$string = "this is an ugly string";
$string = explode(" ", $string );
echo $pieces[0]; // this
echo $pieces[1]; // is
echo $pieces[2]; // an
echo $pieces[3]; // ugly
echo $pieces[4]; // string
It puts it into an array so you just need to loop through that array.
$string = "this is an ugly string";
$string = explode(" ", $string );
echo $pieces[0]; // this
echo $pieces[1]; // is
echo $pieces[2]; // an
echo $pieces[3]; // ugly
echo $pieces[4]; // string
It puts it into an array so you just need to loop through that array.
#3
Posted 19 March 2007 - 07:57 AM
<?php
$string = explode(' ', 'this is an ugly string'); //break down the sentence
foreach($string as $str){ //loops through the array
mysql_query("INSERT INTO tablename (id, word) VALUES (null, '$str')"); //query
}
?>
commented
#4
Posted 19 March 2007 - 07:27 PM
I prefer preg_split over explode, although explode will work.
Doesn't hurt giving another way to do it though
Doesn't hurt giving another way to do it though
<?php
$mystring = "this is an ugly string";
$words = preg_split("#\s#", $mystring, -1, PREG_SPLIT_NO_EMPTY);
foreach ($words AS $word)
{
mysql_query("
INSERT INTO table (word)
VALUES ('$word')
");
}
?>
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users
