0

This may be a little elementary for some, but in something like the following statement what would happen if the string was an integer (e.x 007 as in the movie):

$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
  1. If colour was '007' would PDO::PARAM_STR, still work?
  2. What is int 12 for? does it refer to the length of (colour & $colour)?
  3. Is it's purpose to maximize the filter? (only strings of 12 get through?)

Thanks guys, still working on deciphering manual (new to PHP) but so far don't see specifics on this.

Complete statement here.

/* Execute a prepared statement by binding PHP variables */

$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
kittykittybangbang
  • 2,380
  • 4
  • 16
  • 27
Magic
  • 67
  • 5
  • 2
    `007` would be treated as an octal, given if you used `$calories = 007;` so you'd need to wrap it in quotes. – Funk Forty Niner Mar 21 '17 at 16:14
  • Yes, I see now, and it looks like in such a scenario I could just filter as any normal string and disregard adding the 12. ...just couldn't find the point of the twelve and wanted to apply code correctly... thanks for insight. – Magic Mar 21 '17 at 17:00

1 Answers1

0

Most of time nothing wrong happens. As far as I know, SQL, just like PHP, is a loosely-typed language that allows you to represent a number as a string, so you can always format integers as strings. There are only few exceptional cases:

  • LIMIT clause in emulation mode or any other SQL clause that just cannot accept a string operand.
  • complex queries with non-trivial query plan that can be affected by a wrong operand type
  • peculiar column types, like BIGINT or BOOLEAN that require an operand of exact type to be bound (note that in order to bind a BIGINT value with PDO::PARAM_INT you need a mysqlnd-based installation).

Now to your example. 007 is actually a string, not integer. You can't get an integer with leading zeros in PHP. But in case there is a real integer, you still can bind it as a string.

What is int 12 for?

This number has a very specific purpose used with stored procedures only and doesn't have any effect on the regular queries.

So you can tell that the example is rather misleading.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • Hey guys, the info is so enlightening. Now just to clarify, I could actually leave the 12 off. a simple: $sth->bindParam(':colour', $colour, PDO::PARAM_STR); in such cases would work equally well? – Magic Mar 21 '17 at 16:41