PHP MySQL Insert Record from Array
From w3cyberlearnings
Contents |
PHP MySQL INSERT Records From an array
Insert a new record using the INSERT Statement.
Syntax
$student_record = array( array("Peeou", "Zhou"), array("Isabel", "Peom"), array("Sophal", "Tang"), array("Chong", "Mok"), array("Ebo", "Kaun")); for ($i = 0; $i < count($student_record); $i++) { // build a sql statement for insert $insert_sql = sprintf("INSERT INTO student (first_name, last_name) VALUES(\"%s\",\"%s\")", $student_record[$i][0], $student_record[$i][1]); // insert to the student table mysql_query($insert_sql, $connection) or die(mysql_error($connection)); echo "id: " . mysql_insert_id() . "<br/>"; // get insert id }
Example 1
<?php define('HOST', 'localhost'); define('USER', 'root'); define('PASS', 'yeething'); define('DBNAME', 'woowood'); $connection = mysql_connect(HOST, USER, PASS); if (!$connection) { die("can not connect to the server!<br/>"); } else { $rdb = mysql_select_db(DBNAME); if (!$rdb) { die("The " . DBNAME . "database could not be selected"); } else { // student array $student_record = array( array("Peeou", "Zhou"), array("Isabel", "Peom"), array("Sophal", "Tang"), array("Chong", "Mok"), array("Ebo", "Kaun")); for ($i = 0; $i < count($student_record); $i++) { // build a sql statement for insert $insert_sql = sprintf("INSERT INTO student ( first_name, last_name) VALUES(\"%s\",\"%s\")", $student_record[$i][0], $student_record[$i][1]); // insert to the student table mysql_query($insert_sql, $connection) or die(mysql_error($connection)); echo "id: " . mysql_insert_id() . "<br/>"; // get insert id } } } mysql_close($connection); ?>
Output
id: 6 id: 7 id: 8 id: 9 id: 10