Array items into different rows

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Array items into different rows

Post 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?
User avatar
Peter Anselmo
Forum Commoner
Posts: 58
Joined: Wed Feb 27, 2008 7:22 pm

Re: Array items into different rows

Post 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');
User avatar
psurrena
Forum Contributor
Posts: 355
Joined: Thu Nov 10, 2005 12:31 pm
Location: Broolyn, NY

Re: Array items into different rows

Post 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());
}
 
Post Reply