24

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
anvd
  • 3,997
  • 19
  • 65
  • 126
  • possible duplicate of [Are PHP MySQLi prepared queries with bound parameters secure?](http://stackoverflow.com/questions/1561586/are-php-mysqli-prepared-queries-with-bound-parameters-secure) – outis Jul 19 '12 at 10:04

1 Answers1

24

No, prepared queries (when used properly) will ensure data cannot change your SQL query and provide safe querying. You are using them properly, but you could make just one little change. Because you are using the '?' placeholder, it is easier to pass params through the execute method.

$sql->execute([$consulta]);

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
SamT
  • 10,374
  • 2
  • 31
  • 39
  • so, something like this? $sql->bind_param('s'); $sql->execute(array($consulta)); – anvd Jun 03 '11 at 20:14
  • Sorta, just loose the bind_param there and you should be good. All your doing is just binding your params when you go to call ->execute(); – SamT Jun 03 '11 at 20:31
  • Not really, it's just the way to do it when you use the '?' placeholder. When you used named placeholders, you need to use ->bind_param(), for example: `$sql = $db->prepare('select location from location_job where location like :item')); $sql->bind_param(':item', $consulta);` – SamT Jun 03 '11 at 20:40
  • 1
    note that if you pass an array to execute after binding params, you'll have issues. see this note on the php.net docs: http://us.php.net/manual/en/pdostatement.execute.php#97531 – damianb Jun 08 '11 at 06:02
  • 3
    One thing to note is that `execute()` can only take an array parameter when using the PDO extension. When using mysqli `execute()` has no parameters so you will need to use `bind_param()`. – phn Mar 22 '17 at 11:01