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
4
  • Both INSERT .. SELECT and INSERT .. VALUES allows to insert more than one row (rather than INSERT .. SET). Commented Aug 23, 2021 at 6:31
  • Or use foreach() loop in your PHP file. But multiple inserts are better. Something like described here stackoverflow.com/questions/1307618/… Commented Aug 23, 2021 at 7:50
  • 1
    Does this answer your question? Insert multiple rows with one query MySQL Commented Aug 23, 2021 at 7:51
  • 1
    stackoverflow.com/questions/12502032/… You can follow this answer. Commented Aug 23, 2021 at 9:49

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.