Jump to content


breaking string and putting mysql.


3 replies to this topic

#1 Macintosh

    Young Padawan

  • Members
  • Pip
  • 28 posts

Posted 19 March 2007 - 06:35 AM

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

#2 Archangel

    P2L Jedi

  • Members
  • PipPipPip
  • 988 posts
  • Gender:Male
  • Location:Indiana
  • Interests:Reading (mainly fantasy books), Gaming (Xbox 360, Wii & PS3), Sports, Outdoor Recreation, Watching/Collecting Movies

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.

#3 Av-

    I Feel Left Out

  • Members
  • PipPipPipPip
  • 1,971 posts
  • Gender:Male
  • Location:10 ft. below sea level

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 SecondV

    Young Padawan

  • Members
  • Pip
  • 28 posts
  • Gender:Male
  • Location:Kentucky
  • Interests:All things PHP &amp; MySQL :)

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