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.

1

1 Answer 1

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.

5
  • so, something like this? $sql->bind_param('s'); $sql->execute(array($consulta));
    – anvd
    Jun 3, 2011 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 3, 2011 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 3, 2011 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: us.php.net/manual/en/pdostatement.execute.php#97531
    – damianb
    Jun 8, 2011 at 6: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, 2017 at 11:01

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.