Page 1 of 1

Inserting Array into Database?

Posted: Wed Oct 24, 2012 12:29 pm
by FrederickGeek8
How do I insert an array into a database? Lets say I want to have tags for posts. How should I go about this? Should I just have it insert
array('tag', 'foo', 'foobar');
or is there some other magical thing I can do?

Also, I could probably figure this out on my own but, how do I divide tags up? If I had a textbox with
foo, tag, foobar, steve, bob, fred
Then how do I insert that into an array?

Re: Inserting Array into Database?

Posted: Wed Oct 24, 2012 1:10 pm
by Temor
You use the explode() function to create an array from a comma separated list.
http://php.net/manual/en/function.explode.php

There are many different methods of getting the array in your database. You could insert is a string using implode()
http://php.net/manual/en/function.implode.php

or you could create a foreach loop and run a query for every tag? ( not very effective, performance wise, but it works )
foreach($tags as $tag){
insert into `tags` $tag;
}

Re: Inserting Array into Database?

Posted: Wed Oct 24, 2012 1:23 pm
by FrederickGeek8
The third option would not work... I would be trying for something like
post_title  post_id  post_body  post_tags

Re: Inserting Array into Database?

Posted: Wed Oct 24, 2012 1:25 pm
by FrederickGeek8
Ooh I could just insert the comma separated tags into the database and when search or outputting, I could just explode it :D

Re: Inserting Array into Database?

Posted: Wed Oct 24, 2012 2:03 pm
by Temor
FrederickGeek8 wrote:Ooh I could just insert the comma separated tags into the database and when search or outputting, I could just explode it :D

yes.

Re: Inserting Array into Database?

Posted: Sat Oct 27, 2012 9:51 pm
by jacek
There are also the serialize() and unserialize() functions
$some_array = array(1, 2, 3);
if you do
$string = serialize($some_array);
$string is now an encoded version of the array $some_array that you can store easily, to get back to the original array you use the opposite function
$some_array = unserialize($string);
The explode method would work fine too but this is a bit more robust, it won't break if one of your values has a comma in it.

Re: Inserting Array into Database?

Posted: Sat Nov 03, 2012 2:09 am
by FrederickGeek8
jacek wrote:There are also the serialize() and unserialize() functions
$some_array = array(1, 2, 3);
if you do
$string = serialize($some_array);
$string is not an encoded version of the array $some_array that you can store easily, to get back to the original array you use the opposite function
$some_array = unserialize($string);
The explode method would work fine too but this is a bit more robust, it won't break if one of your values has a comma in it.
Ooh this seems nice :3 thanks!