How To Insert Multiple Rows with a SELECT Statement

Q

How To Insert Multiple Rows with a SELECT Statement? - MySQL FAQs - Managing Tables and Running Queries with PHP Scripts

✍: FYIcenter.com

A

If want to insert rows into a table based on data rows from other tables, you can use a sub-query inside the INSERT statement as shown in the following script example:

<?php
  include "mysql_connection.php";

  $sql = "INSERT INTO fyi_links"
      . " SELECT id+1000, url, notes, counts, time"
      . " FROM fyi_links";
  if (mysql_query($sql, $con)) {
    print(mysql_affected_rows() . " rows inserted.\n");
  } else {
    print("SQL statement failed.\n");
  }

  mysql_close($con); 
?>

If you run this script, you will get something like this:

2 rows inserted.

2007-05-10, 6616👍, 0💬