Insert Multiple records in MySQLi database table

Insert Multiple records in MySQLi database table

In my previous post, you know how to insert single record in database table using MySQLi preapred statements. Now i am going to tell you how to insert multiple record at once in MySQLi database tables.

To insert multiple records at once in MySQLi database table, you will have to include multiple lists of column values enclosed within parentheses and must be separated by (,) commas.

You can also know how many rows are affected by using mysqli_affected_rows.

Please have a look on given example :

  1. if (!$db->query("INSERT INTO products(id) VALUES (1), (2), (3), (4)")) {
  2. echo "Error: (" . $db->errno . ") " . $db->error;
  3. }else{
  4.     print 'Successfully inserted and Total ' .$db->affected_rows .' rows added.';
  5. }
  6. ?>
Example 1 :

  1. //product 1
  2. $product_name1 = '"'.$db->real_escape_string('ExpertPHP').'"';
  3. $product_price1 = '"'.$db->real_escape_string('60000').'"';
  4. $product_details1 = '"'.$db->real_escape_string('Provide Online Tutorials').'"';
  5. //product 2
  6. $product_name2 = '"'.$db->real_escape_string('Demo').'"';
  7. $product_price2 = '"'.$db->real_escape_string('60000').'"';
  8. $product_details2 = '"'.$db->real_escape_string('Demo code').'"';
  9. //Insert multiple rows
  10. $insert = $db->query("INSERT INTO products(product_name, product_price, product_details) VALUES
  11. ($product_name1, $product_price1, $product_details1),
  12. ($product_name2, $product_price2, $product_details2)");
  13. if($insert){
  14. //know total inserted records using mysqli_affected_rows
  15. print 'Successfully inserted and Total ' .$db->affected_rows .' rows added.';
  16. }else{
  17. echo "Error: (" . $db->errno . ") " . $db->error;
  18. }
Example 2 :

  1. $sql = "INSERT INTO products (product_name, product_details)
  2. VALUES ('ExpertPHP', 'Online PHP Tutorials');";
  3. $sql .= "INSERT INTO products (product_name, product_details)
  4. VALUES ('Demo','Demo code');";
  5. if ($db->multi_query($sql) === TRUE) {
  6. echo "records inserted successfully";
  7. } else {
  8. echo "Error: " . $sql . "
    "
    . $db->error;
  9. }
  10. $db->close();

Phone: (+91) 8800417876
Noida, 201301
sakarya escort akyazı escort arifiye escort erenler escort eve gelen escort ferizli escort geyve escort hendek escort otele gelen escort sapanca escort söğütlü escort taraklı escort
sakarya escort - akyazı escort - arifiye escort - erenler escort - eve gelen escort - ferizli escort - geyve escort - hendek escort - karapürçek escort - karasu escort - kaynarca escort - kocaali escort - otele gelen escort - pamukova escort - sapanca escort - söğütlü escort - taraklı escort
sapanca escort hendek escort karasu escort escort sakarya sakarya escort bayan adapazarı escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort