Hello let me get right too it I have an array whit a bunch of tags $a=array("Dog","Cat","Horse"); PHP: I would like to insert it into a mysql database but with each item seperated by , so in the database it would look like; Dog, Cat, Horse How can i do this the idea i have in mind is to run a foreach loop; foreach ($a as $tags) { $tags=$tags.", "; $query=mysql_query("UPDATE table_name SET tags='$tags' "); } PHP: But i feel like this is a bit of overkill Is there a better or more cleaner way to get the same end result any help with this would be greatly appreciated Thanks
Do you want a separate record for each element of the array (IOW, Dog in ione record, Cat in the next record ... and display that field for all records with commas between them) or do you want all of them in the same record as one long string "Dog, Cat, Horse, ..."? Your description seems to say the latter, but the data wouldn't be very useful that way.
Hello Rukbat Thanks for replying to my question Yes i would like it all to be in one single string then enter that string into my database You mentioned that the data would not be useful and you sorta right for instance if the if i wanted to do a search for rows with the word cat in it, it seems like a row like - Dog, Cat, Horse would not return any thing unless the string am searching for(which is cat in this case) is at the end like so - Dog, Horse, Cat not sure if that's what you meant but i noticed that it seems to play out that way my next option would be to create a seperate table for tags and enter the "tag" post "id" like for example 'dog' '100' 'horse' '100' 'cat' '100' let me know if you know of a better way thanks
I'd actually have to see the entire database, all the code and know what you're trying to accomplish. But basically if you want to store an array in a single field in a single record, you use a loop. And to select the record you use LIKE, not =, in the WHERE clause.
To do what you're asking for cleanly, jadexe's solution is the way to go. And when you bring your string back out of the database, you simply reverse the process with explode. $tags = array("Dog", "Cat", "Horse"); $query = "insert into `table` ( `otherInfo`, `tags` ) values ( 'Other Information', " . implode(",", $tags) . " )"; //insert record //later on... $object = mysql_fetch_object(mysql_query("select * from `table` where `id` = " . $id)); $tags = explode(",", $object->tags); for ($i = 0, $l = count($tags); $i < $l; ++$i) { echo "<li>" . $tags[$i] . "</li>"; } Code (markup): Hope this helped.
Nothing really wrong with it - it works. But since there's a native function that can replace the foreach loop, it should be used. More efficient, plus there's fewer lines of code to maintain. Might not make a huge difference on a small script, but it's little things like this that add up in larger code bases that can lead to performance bottlenecks and code maintainability issues.