1

I'm using prepared statements in PDO to select some data from my SQL server and I'm getting a syntax error:

QLSTATE[HY000]: General error: 10007 Incorrect syntax near 'memb_user'. [10007] (severity 5) [(null)] in

memb_user is the table name. Here is the prepared statement and the array that I'm using:

$query =   "SELECT ?, ? FROM ? WHERE ? = ? AND ? = ?";

   $data    =   array($this->columns['username'], $this->columns['password'], $this->table,
                      $this->columns['username'], $this->user , $this->columns['password'], $this->pass);

And this is how I'm executing the statement:

$statement  =   $this->connection->prepare($query);
        $statement->execute($data);

I've tried putting the query into sql server and replacing the placeholder with correct values and it seems to be okay, only thing that was of concern was the quotes that needed to be in the WHERE conditionals. So am I executing this incorrectly?

jn025
  • 2,755
  • 6
  • 38
  • 73
  • 2
    You can't use placeholders for column or table names -> `SELECT ?, ? FROM ?`, only for values. – Sean Nov 11 '14 at 04:28

1 Answers1

1

As @sean said, "You can't use placeholders for column or table names." You can however, inject them into the query via sprintf() NOTE: Ensure all POST/GET data is properly escaped.

Try this: (untested)

$query = sprintf('SELECT `%1$s`, `%2$s` FROM `%3$s` WHERE ? = ? AND ? = ?', $this->columns['username'], $this->columns['password'], $this->table);

$data  = array($this->columns['username'], $this->user , $this->columns['password'], $this->pass);
Nicholas Summers
  • 4,444
  • 4
  • 19
  • 35
  • Thanks for the answer, wasn't aware that column or table names can't be place holders. Putting the column/table variables in normally fixed the issue. – jn025 Nov 11 '14 at 05:52