0

I have a little PHP script which just needs to get all the rows from a table in a SQLite database. The name of the table is always something like 174597131028398082-199534472775860224.

This name is composed from two variables (sid and cid) which are defined through the parameters of a GET request. The problem is that instead of returning all the rows (which I would display later in the script), I get this error : SQLSTATE[HY000]: General error: 1 no such table: :sid-:cid.

It seems like PHP does not replace :sid and :cid with the correct values. I've seen another thread about a similar problem, but I still can't get it working.

Here's my code :

$query = "SELECT * FROM `:sid-:cid`;";

$queryparams = array(
    ':sid' => $_GET['sid'],
    ':cid' => $_GET['cid']
);

try {
  $stmt = $db->prepare($query);
  $result = $stmt->execute($queryparams);
} catch(PDOException $ex) {
  die($ex->getMessage());
}

Also, here is how I connect to the database :

try {
  $db = new PDO("sqlite:scores.db");
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $ex) {
  die($ex->getMessage());
}
Community
  • 1
  • 1
  • 1
    Table and Column names cannot be replaced by parameters in PDO. – Saty Aug 04 '16 at 13:57
  • 1
    Oww. So there's no way to do what I want? :x – user5191848 Aug 04 '16 at 13:58
  • @Saty strange you can't do that. I don't really know php, but is there a difference between a string passed as an argument and a string built from variables? – WayToDoor Aug 04 '16 at 14:01
  • 2
    Check http://stackoverflow.com/questions/182287/can-php-pdo-statements-accept-the-table-or-column-name-as-parameter – Saty Aug 04 '16 at 14:02
  • 1
    Whitelist and interpolate those values instead. Binding them won't work in any database. Btw, it also indicates a slight database misdesign. There's little reason to have multiple tables with the same structure. Instead include them as primary columns in a compound table. – mario Aug 04 '16 at 14:06
  • 1
    Well at least now I know. Thanks! I'll try what you suggested. – user5191848 Aug 04 '16 at 14:14

0 Answers0