Loading lesson path
Formula
SQL Prepared Statements - Prevent SQL InjectionSQL prepared statements can be used to protect a web site from SQL injections. Prepared statements seperates the query structure (the SQL) from the actual data (user input). Prepared statements basically work like this:
An SQL query template with placeholders is sent to the server. The data values are not sent. Example: INSERT INTO MyGuests VALUES(?, ?, ?). Then, the server parses, compiles, and optimizes the SQL query template, without executing it
At a later time, the application binds the values to the parameters, and the database executes the query. The application may execute the query as many times as it wants with different values Prepared statements have four main advantages:
PHP MySQL Prepared Statements, and uses prepared statements in MySQL:
Example - MySQL with Prepared Statements <?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}// SQL query template
$sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)";
// Prepare the SQL query template if($stmt = $conn->prepare($sql)) {// Bind parameters
$stmt->bind_param("sss", $firstname, $lastname, $email);//
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$stmt->close();
$conn->close();?>
In the SQL, the question marks (?) are placeholders for firstname, lastname, and email values:
"INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"
Now, look at the bind_param() function. This function bind variables to the placeholders in the SQL query. The placeholders (?) will be replaced by the actual values held in the variables at the time of execution. The "sss" argument lists the type of data each parameter is. The scharacter tells mysql that the parameter is a string. We must define one of these for EACH parameter. By telling mysql what type of data to expect, we minimize the risk of SQL injections:
$stmt->bind_param("sss", $firstname, $lastname, $email);The type argument can be one of four types: i - integer (whole number) d - double (floating point number) s - string (text) b - binary (image, PDF, etc.)
If we want to insert data from external sources (like user input), it is very important that the data is sanitized and validated.