Given the following piece of code, Do i need to escape and sanitize $city
?
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$city = "Amersfoort";
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $city);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($district);
/* fetch value */
$stmt->fetch();
printf("%s is in district %s\n", $city, $district);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
Do you need to sanitize any input when using prepared queries?
Therefore, to safeguard the database from hackers, it is necessary to sanitize and filter the user entered data before sending it to the database.
The Basics. The first lesson anyone learns when setting up a web-to-database—or anything-to-database gateway where untrusted user input is concerned—is to always, always sanitize every input.
An application receives queries and requests from untrusted sources that might expose the system to malicious attacks. Input sanitization ensures that the entered data conforms to subsystem and security requirements, eliminating unnecessary characters that can pose potential harm.
Sanitizing data means removing any illegal character from the data. Sanitizing user input is one of the most common tasks in a web application. To make this task easier PHP provides native filter extension that you can use to sanitize the data such as e-mail addresses, URLs, IP addresses, etc.
No you don't have to escape it or sanitize it for injection protection. For other app specific things you may sanitize it though.
I had a similar question a while back:
mysqli_stmt_bind_param SQL Injection
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With