3

I want to bind variables instead of just building SQL strings. Anyway to do this in Php?

Either MySQL or PostgreSQL answers would help.

Thanks

jww
  • 97,681
  • 90
  • 411
  • 885
Robert Gould
  • 68,773
  • 61
  • 187
  • 272

4 Answers4

8

There's e.g. PDO.
An introduction to pdo and prepared statements (including bound parameters) is located at http://docs.php.net/pdo.prepared-statements

VolkerK
  • 95,432
  • 20
  • 163
  • 226
  • carefull with PDO::bindParam: http://stackoverflow.com/questions/833510/php-pdobindparam-data-types-how-does-it-work – Strae Dec 14 '09 at 13:21
4

You should read on the MySQL Improved Extension (MySQLi) at http://php.net/manual/en/book.mysqli.php , and on prepared statements

sp.
  • 1,336
  • 11
  • 7
2

For Postgres specifically - pg_query_params (and pg_send_query_params) is the most primitive form of binding but still very useful.

And then there's PDO but the others already mentioned it.

Milen A. Radev
  • 60,241
  • 22
  • 105
  • 110
0

There are a couple of flavors. I believe the more savvy individuals here will push for you to use PDO prepared statements. There is also a sprintf() version.

PDO

An answer has already been discussed on StackOverflow here.

SPRINTF

$sql = sprintf('SELECT * FROM table WHERE id = %d AND field = %s',
               $id,
               mysql_real_escape_string($value));
Community
  • 1
  • 1
Corey Ballou
  • 42,389
  • 8
  • 62
  • 75
  • 3
    how sprintf is a bind variables replacemet? there are no DB checks on the variables content. This is as not safe as the plain text stuff – Genry Sep 30 '12 at 19:31
  • 1
    The sprintf version is vulnerable to sql injection and should not be used. – jbo5112 Feb 25 '14 at 03:14