Final: Tutorial 2
Brief
This is a quick tutorial of doing inserts using the mysqli prepared statements
Prepared Statement using INSERT
<?php
// Call predefined Connection Object stored in an external file
require_once($_SERVER['DOCUMENT_ROOT'].'/path/externalconnectionfile.php');
// Some local variables to be used
$var1 = 'value';
$var2 = 'value';
$var3 = 'value';
// Set up the insert to a table using prepared statements
$stmt = mysqli_stmt_init($link); //$link is declared in the connection object
// Set up the SQL statement
$sql = "INSERT INTO table (field1, field2, field3) VALUES (?, ?, ?)";
// Prepare query to be run by making sure you have a working query and connection
if(mysqli_stmt_prepare($stmt, $sql)) {
// Bind local variables that have pre-assigned values to the prepared statement
// Within the quotes are data type declarations: s = string; i = integer; d = double; b = blob
mysqli_stmt_bind_param($stmt, "iss", $var1, $var2, $var3);
//Get back the results of the insert statement -- Will return True or False
$result_query = mysqli_stmt_execute($stmt);
// Test to see if the insert was successful
if($result_query == true){
// assume that the record was created and a new id was created using an auto_incrementing field,
// we can capture that value using this PHP function and assign it to a local variable
$newid = mysqli_insert_id($link);
}
// Close the prepared statement
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>
Login or Register to post a comment