Jump to: navigation, search

PHP MySQLi Insert Records Using Binding

From w3cyberlearnings

Contents

PHP MySQLi Insert Records

Insert records to the table using binding.

Syntax x1

"si", s for string, and i is for integer.

$query = "INSERT INTO student (name, age) VALUES(?, ?)";
$conn = $db->prepare($query);
$conn->bind_param("si", $v[0], $v[1]);
$conn->execute();

Example 1

<?php

define('HOST', 'localhost');
define('USER', 'user2000');
define('PASS', 'password2000');
define('DBNAME', 'w3cyberlearning');

$db = new mysqli(HOST, USER, PASS, DBNAME);
// records
$student_records = array(
	 array('Bob', 39),
	 array('Jing', 41),
	 array('Paul', 42),
	 array('David', 40),
	 array('Jamy', 20),
	 array('Christ', 28)
);

// array to store insert id
$insert_id = array();

if ($db->connect_errno) {
	echo "Failed to connect to MySQL: (" 
           . $db->connect_errno . ") " . $db->connect_error;
}

$query = "INSERT INTO student (name, age) VALUES(?, ?)";

$conn = $db->prepare($query);

foreach ($student_records as $v) {
	$conn->bind_param("si", $v[0], $v[1]);
	$conn->execute();
	$insert_id[] = $conn->insert_id;
}

if (count($insert_id) > 0) {
	print_r($insert_id);
}


$db->close();
?>

Output

Do not try to refresh the page, you will insert multiple records for each time you refresh or run the program.

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)



<sidebar>

    • PHP MySQL mysqli|PHP MySQL mysqli
    • PHP MySQLi Connect|PHP MySQLi Connect
    • PHP MySQLi Create Table|PHP MySQLi Create Table
    • PHP MySQLi Insert Records Using Binding|PHP MySQLi Insert Records use Binding
    • PHP MySQLi Fetch Records as an associative array|PHP MySQLi Fetch Records as an associative array
    • PHP MySQLi Fetch All Records|PHP MySQLi Fetch All Records
    • PHP MySQLi Fetch Records And Bind to variables|PHP MySQLi Fetch Records And Bind to variables
    • PHP MySQLi Fetch as object|PHP MySQLi Fetch as object
    • PHP MySQLi Fetch Records Use binding|PHP MySQLi Fetch Records Use binding
    • PHP MySQLi Update Records and Return affected rows|PHP MySQLi Update Records and Return affected rows
    • PHP MySQLi Delete Records Use binding|PHP MySQLi Delete Records Use binding

</sidebar>

Navigation
Web
SQL
MISC
References