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?
Array items into different rows
Moderator: General Moderators
- Peter Anselmo
- Forum Commoner
- Posts: 58
- Joined: Wed Feb 27, 2008 7:22 pm
Re: Array items into different rows
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
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());
}