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

Gary Willoughby picture Gary Willoughby · Jan 20, 2011 · Viewed 9.4k times · Source

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?

Answer

profitphp picture profitphp · Jan 20, 2011

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