//These are PHP superglobals
$_POST: Collect data submitted from forms
$_GET: Collect data sent from the URL
$_SESSION: Store data across multiple pages for a single user session
$_COOKIE: Store data on user browser for persistent tracking
<?php
//mysqli_* functions
//Look for the purple text, that is where the description of a
//function start
stmt: abbreviation for statement
Order: -->init-->prepare-->bind_param-->execute-->store_result
-->mysqli_stmt_init: create a new mysqli_stmt object, which will be
used to execute a prepared statement
Ex: $stmt=mysqli_stmt_init($conn);
-->mysqli_stmt_prepare: prepare an SQL statement for execution
Ex:
$sql="INSERT INTO CONTACTS (name, phone, comment) VALUES (?,?,?)";
mysqli_stmt_prepare($stmt,$sql); //? acts as placeholder for what
//will be bound later
-->mysqli_stmt_bind_param: bind variables to placeholders in the
the prepare statement. Types of the variables are specified by
these letters:
- "i" for integer
- "d" for double
- "s" for string
- "b" for blob (Binary Large Objects: image, video, audio,...)
Ex:
$name= "John Gotti";
$phone="111-2222";
$comment="Boss of Gambino family";
mysqli_stmt_bind_param($stmt,"sss",$name,$phone,$comment);
//Here, "sss" indicates that all 3 fields $name, $phone, and
//$comment are string
-->mysqli_stmt_execute: Execute a prepared statement with the
boundedvariables
Ex:
mysqli_stmt_execute($stmt);
-->mysqli_stmt_store_result: store the result to the client, allowing
you to fetch the result later
Ex:
mysqli_stmt_store_result($stmt);
//Example using all these in db-action-contact.php
include 'db.php';
$action = $_POST['action'];
if ($action == "add") {
$name = $_POST['name'];
$phone = $_POST['phone'];
$comment = $_POST['comment'];
// Initialize statement object
$stmt = mysqli_stmt_init($conn);
// Prepare the SQL statement
$sql = "INSERT INTO contacts (name, phone, comment) VALUES (?, ?, ?)";
mysqli_stmt_prepare($stmt, $sql);
// Bind parameters to the placeholders
mysqli_stmt_bind_param($stmt, "sss", $name, $phone, $comment);
// Execute the statement
if (mysqli_stmt_execute($stmt)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Close the statement
mysqli_stmt_close($stmt);
} elseif ($action == "update") {
$id = $_POST['id'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$comment = $_POST['comment'];
// Initialize statement object
$stmt = mysqli_stmt_init($conn);
// Prepare the SQL statement
$sql = "UPDATE contacts SET name=?, phone=?, comment=? WHERE id=?";
mysqli_stmt_prepare($stmt, $sql);
// Bind parameters to the placeholders
mysqli_stmt_bind_param($stmt, "sssi", $name, $phone, $comment, $id);
// Execute the statement
if (mysqli_stmt_execute($stmt)) {
echo "Record updated successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Close the statement
mysqli_stmt_close($stmt);
}
mysqli_close($conn);
?>