1

Is it possible to do a bindvalue for the table name? mine doesn't seem to pick it up basically the second 2 binds work fine if I remove the :table and add the tablename instead, but I want to use this for more than one table from the same form.

The field for table on the form is defined from a result of the previous query so the table name appears on the form in a value as $table which displays correctly so this should post the value of $table to the table bind???

try {
    $sql = 'UPDATE :table SET
                archive = :archive
                WHERE id = :id';
    $s = $pdo->prepare($sql);
    $s->bindvalue('table', $_POST['table']);
    $s->bindvalue('archive', $_POST['archive']);
    $s->bindvalue('id', $_POST['id']);
    $s->execute();
}
Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
easono
  • 15
  • 2
  • 5

1 Answers1

1

Since prepared statements are a "bit" more than sprintf, it doesn't make sense to set the table by variable.

A prepared statement is passed to the DB before the actual values are set. So the DB may look for a way how to answer the query. After this preparation the actual values searched for are set. The query is answered, when execute() is called.

So, to prepare "a way how to answer the query" (as I called it), the table name is a significant information. That is why it does not make sense to pass it as a variable. That is also why it doesn't work.

So, you have to string concatenate the table name:

$sql = 'UPDATE '. $table .' SET
            archive = :archive
            WHERE id = :id';

As @zerkms suggest, you should whitelist the possible table names.

Raul Pinto
  • 1,095
  • 8
  • 15