Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do i need to sanitize input if using prepared PHP/MySQL queries?

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?

like image 760
Gary Willoughby Avatar asked Jan 20 '11 20:01

Gary Willoughby


People also ask

Is sanitization compulsory in PHP?

Therefore, to safeguard the database from hackers, it is necessary to sanitize and filter the user entered data before sending it to the database.

Should you sanitize user input?

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.

Why must you always sanitize user inputs before using them in your queries?

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.

What is input sanitization in PHP?

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.


1 Answers

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

like image 52
profitphp Avatar answered Oct 19 '22 22:10

profitphp