Is mysql_real_escape_string() necessary when using prepared statements?

anvd picture anvd · Jun 3, 2011 · Viewed 7.4k times · Source

For this query, is necessary to use mysql_real_escape_string?

Any improvement or the query is fine ?

$consulta = $_REQUEST["term"]."%";

($sql = $db->prepare('select location from location_job where location like ?'));

$sql->bind_param('s', $consulta);
$sql->execute();
$sql->bind_result($location);

$data = array();

while ($sql->fetch()) {
    $data[] = array('label' => $location);
}

The query speed is important in this case.

Answer

SamT picture SamT · Jun 3, 2011

No, prepared queries (when used properly) will ensure data is properly escaped for safe querying. You are kind of using them properly, just need change one little thing. Because you are using the '?' placeholder, it is better to pass params through the execute method.

$sql->execute(array($consulta));

Just be careful if you're outputting that to your page, database sanitization does not mean it will be safe for display within HTML, so run htmlspecialchars() on it as well.