Jump to: navigation, search

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


Related Links


  1. MySQL Connect
  2. Create Database
  3. Connect to Database
  4. Delete Database
  5. Create Table
  6. Insert Record
  7. Insert From Array
  8. Insert From File
  9. Update Record
  10. Query Single Record
  11. Query Multiple Records
  12. Query Uses LIMIT
  13. Query Uses ORDER BY
  14. Delete Table
  1. Create Two Tables for this section tutorial
  2. Query Uses AND Operator
  3. Query Uses OR Operator
  4. Query Uses INNER JOIN
  5. Query Uses LEFT OUTER JOIN
  6. Query Uses RIGHT OUTER JOIN
  7. Query with Subquery
  1. MySQL Aggregate Count
  2. MySQL Aggregate SUM
  3. MySQL Aggregate MAX
  4. MySQL Aggregate MIN
  5. MySQL Aggregate AVG
  6. MySQL Query Uses GROUP BY
  7. MySQL Query Uses Having
  1. PHP MySQL Create Date
  2. PHP MySQL Insert Date
  3. PHP MySQL Query Date
Navigation
Web
SQL
MISC
References