Prepared Statements and Bound Parameters
A prepared statement is a method, or feature used in performing the same work procedure php programming is doing, but on a more secure version.
Why Prepared Statement in Php
Ever since php built websites has been facing a lot of challenges from sql attacks, prepared statement has been the only feature you can use to avoid being hacked with sql injections.
So you need to know this very well.
How Does Prepared Statement Works
Php prepared statement work on parameters. to trick the statement not to execute immediately the function is called.
We want to insert a data inside our database, and we don't want a simple code to be triggered into our website database.
Now, let us take for example, we have an input field and we want to make a sign-up system where a users username and password will be stored inside our database.
Now, for example the user inserted a SQL statement to destroy our database. Like ' DROP table
Now that user try's to drop our table, so to prevent this we need to look for a way to make the input field have no effect on our website database.
Then that is where sql parameters comes in.
We'll say from our php mysqli file.
The prepared statement we are using will be in two ways, the procedure ways and the advanced way.
Prepared Statement The Procedure Ways
The Advanced Way
$name = 'Emmanuel';
$password = sha1('password');
$sql = "INSERT INTO users (name,password) VALUES (?,?);
Prepared Statements in PDO
The following example uses prepared statements and bound parameters in PDO:
Example (PDO with Prepared Statements)
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "firstname.lastname@example.org";
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (:firstname, :lastname, :email)");
echo "New records created successfully";
echo "Error: " . $e->getMessage();
$conn = null;