23

In PHP with PDO, what characters are we limited to using. I've tried looking in the documentation and online but to no avail.

I did find a post where a user had used a hypen in the name which broke the query. I'm writing a function that dynamically generates these names and since hyphens are no nos, I was wondering if there was a list of alternatives.

<?php
/* 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();
?>

So in this example what characters would be allowed in the string ':colour'?

SeanDowney
  • 17,368
  • 20
  • 81
  • 90

2 Answers2

38

The easiest way to find out, is to just check the source code:

BINDCHR     = [:][a-zA-Z0-9_]+;

You can use alphanumeric + underscore.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
NikiC
  • 100,734
  • 37
  • 191
  • 225
  • 3
    Just looking at the source I can see bugs in there... their comment expression is wrong. `--` must be followed by whitespace, not just any non-linebreak char. – mpen May 20 '13 at 04:02
  • 2
    Hasn't changed for [PHP 5.6](http://lxr.php.net/xref/PHP_5_6/ext/pdo/pdo_sql_parser.re#49) if anyone's interested. – mpen Feb 23 '15 at 23:57
10

If I read the PDO SQL parser source code correctly, it's alphanumeric characters plus underscore.

Sander Marechal
  • 22,978
  • 13
  • 65
  • 96