0

how can I insert multiple rows into MySQL with php so that after one single query the MySQL Table would look like:

user_id Message Date Subject
1243 Hello world! 06.04.2021 First Message
 5265 Hi John!  07.04.2021 Second Message
  • Both INSERT .. SELECT and INSERT .. VALUES allows to insert more than one row (rather than INSERT .. SET). – Akina Aug 23 '21 at 06:31
  • Or use foreach() loop in your PHP file. But multiple inserts are better. Something like described here https://stackoverflow.com/questions/1307618/multiple-mysql-insert-statements-in-one-query-php/1307652 – milenmk Aug 23 '21 at 07:50
  • 1
    Does this answer your question? [Insert multiple rows with one query MySQL](https://stackoverflow.com/questions/12502032/insert-multiple-rows-with-one-query-mysql) – milenmk Aug 23 '21 at 07:51
  • 1
    https://stackoverflow.com/questions/12502032/insert-multiple-rows-with-one-query-mysql You can follow this answer. –  Aug 23 '21 at 09:49

1 Answers1

1

You can use MYSQL prepared statement

    include(your connection code...)

    // prepare and bind
    $stmt = $conn->prepare("INSERT INTO yourtable(user_id, message, date, subject) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("isss", $user_id, $message, $date, $subject);

    @foreach statement for your data
    
    // set parameters and execute
    $user_id= $data->id;
    $message= $data->message;
    $date= $data->date;
    $subject= $data->subject;
    $stmt->execute();
    
    @endforeach

this method can even secure your app from SQL injection

adam
  • 347
  • 2
  • 7