Page 1 of 1

Array items into different rows

Posted: Wed Dec 10, 2008 5:12 pm
by psurrena
Say you have a person and that person is making a shopping list

Person: Tom
Items: cake, flowers, dog food

Is it possible to write a query that would insert to the database:
row 1: tom | cake
row 2: tom | flowers
row 3: tom | dog food

Or would you have to use foreach and run a new query for each item?

Is it just better to to the array and implode it after the fact?

Re: Array items into different rows

Posted: Wed Dec 10, 2008 6:19 pm
by Peter Anselmo
You can certainly do it with one query, however you may have to use a loop to create that query.

Code: Select all

insert into shopping_list
(name,item)
values
('tom','cake'),
('tom','flowers'),
('tom','dog food');

Re: Array items into different rows

Posted: Thu Dec 11, 2008 11:13 am
by psurrena
Thanks, here's it is:

Code: Select all

 
if(isset($_POST['favorites'])){
    $sql.="INSERT INTO people_favorites (people_id, favorites_id) VALUES ";
 
    foreach($_POST['fav'] as $value){
        $a[]="('$id','$value')";
    }
 
    $sql.= implode(", ",$a);
 
    $result=mysql_query($sql) or die (mysql_error());
}