PHP Prepare Statement


PHP Prepare Statement :– Whether you’re reading from, or writing to a database, using prepared statements are easy, convenient, and secure. So what are they?

If you look at an HTML file, you’ll see that it’s carrying both the content and instructions on how to show it. Commonly SQL queries are written the same way. The problem with that is that if you’re not careful, you (or more annoyingly, someone else) can write content that gets mistaken for commands. In HTML, that ends up with broken layouts or cross-site scripting attacks, but with databases it can hand over all your data to attackers.

With HTML the only answer is to always escape your content so it can never be interpreted as HTML tags when you don’t want it to. You can do that with your SQL too, by using your database’s escaping functions (like mysql_real_escape_string()), but there’s a better way, which is to use a prepared statement. With this method, your command and the content are sent along separate channels to the database, which means you never need to worry about things like SQL injection attacks.

Prepared statements are also faster if you’re running the same query often, since your database won’t need to interpret the command every time it’s sent.

Example // How to add records using prepare statement

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "employee";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
// prepare and bind
$sql="INSERT INTO JohnData (firstname, lastname, email) VALUES (?, ?, ?)";
if($stmt = $conn->prepare($sql)){
	
$stmt->bind_param("sss", $firstname, $lastname, $email);

// set parameters and execute
$firstname = "Adam";
$lastname = "Smith";
$email = "adam@example.com";
$stmt->execute();

$firstname = "Riley";
$lastname = "Leah";
$email = "riley@example.com";
$stmt->execute();

$firstname = "Camila";
$lastname = "Paisley";
$email = "Camila@example.com";
$stmt->execute();

echo "Prepared statements are very useful against SQL injections";
}
else{
    echo "ERROR: Could not prepare query: $sql. " . $conn->error;
}
//$stmt->close();
$conn->close();
?>

Advertisements

Add Comment

đź“– Read More