Filippo oretti
Filippo oretti

Reputation: 49873

MySQL - easiest way to insert multiple table rows - doing a foreach

Ok i have 2 tables,

users_table: id | firstname

messages_table : id | id_to | id_from | message

what i'm trying to do now is getting all users_table ID and insert for each one id a message in messages_table (so send messages to all users using one query)

i'm trying somenthing like this :

foreach $users_table.id do:

    INSERT INTO messages_table (id_to,id_from,message) VALUES ($users_table.id, 5, "Hey man!");

Can i do that without a server side script?

Upvotes: 0

Views: 95

Answers (1)

Sirko
Sirko

Reputation: 74086

You can use a INSERT ... SELECT statement as long as the other parameters are constant (or can be derived from other tables):

INSERT INTO `message_table` ( `id_to`, `id_from`, `message`)
SELECT user.`id`, 5, "Hey man!"
  FROM `users_table` user

Upvotes: 2

Related Questions