A prepared statement is a feature used to execute the same/similar SQL statement repeatedlly with high efficiency.
Prepared statement basically work like this:
Prepared: An SQL statement template is created and sent to the database.Certain values are left unspecified, called parameters(?)
The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it.
Execute: At a later time, the application binds the values to the parameters, and the database executes the statement.The application may execute the statement as many times as it wants with differenet values.
Compared to executing SQL statements directly, prepared statements have 2 main advantages:
Prepared statements reduces parsing time as the preparation on the query is done only once
Bound parameters minimize bandwidth to the server as you need send only the parameters each time, and not the whole query
Prepared statements are very useful against SQL injections, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped.If the original statement template is not derived from external input, SQL injection cannot occur.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn -> connect_error){
die("Connection failed:" . $conn -> connect_error);
}
$stmt = $conn ->prepare("INSERT INTO MyTable(firstname, lastname, email) VALUES (?, ? , ?)");
<!-- the first paramters tells the database what the parameters are sss means three parameters are all string type -->
<!-- i --integer d -- double s--string b--BLOB -->
$stmt ->bind_parem("sss", $firstname, $lastname, $email);
$firstname = "John";
$lastname = "Doe";
$email = "[email protected]";
$stmt -> execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "[email protected]";
$stmt -> execute();
$stmt -> close();
$conn -> close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try{
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn ->prepare("INSERT INTO MyTable(firstname, lastname, email) VALUES(:firstname, :lastname, :email)");
$stmt ->bindParam
}catch(PDOException $e){
error "Errpr: " .$ e -> getMessage();
}
$conn = null;
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn -> connect_error){
die("Connection failed:" . $conn -> connect_error);
}
if($result -> num_rows > 0){
while($row = $result -> fetch_assoc()){
echo "id:" .$row["id"]. "- Name:" . $row["fistname"] . " " .$row["lastname"] . "<br>";
}
}else{
echo "0 results";
}
$conn -> close();
?>