1

According to Doctrine's documentation it is possible to bind parameters to a query. Example:

$qb->select('u')
   ->from('User u')
   ->where('u.id = ?1')
   ->orderBy('u.name', 'ASC')
   ->setParameter(1, 100);

Derived from this question I would like to know if it is possible to parametrize the select and the from statement as well? Like

$qb->select('?1')
   ->from('?2 u')
   ->where('u.id = 2')
   ->orderBy('u.name', 'ASC')
   ->setParameters(array(1 => 'mytable', 2 => 'mycolumn'));

I didn't manage to do so, but maybe I just did not know the proper way. Does anyone?

Community
  • 1
  • 1
Gottlieb Notschnabel
  • 9,408
  • 18
  • 74
  • 116

1 Answers1

2

This is the way prepared statements work with PDO. The query and the statement are being send seperately. This allows your database to calculate the optimal query path for your query. The query path then makes use of the parameters to get the right results. The query path will try to optimize speed for the next time you make the same query. So for select and from you just have to do select($select). Note that the optimization will be lost of you put a new select each time.

Update:
This is a related answer: https://stackoverflow.com/a/182353/1833322

This is an example of how it should look in DQL:

$query = $em->createQuery('SELECT x FROM '.$mappingPlusEntity.' x WHERE x.id = ?1');
$query->setParameter(1, 321);
Community
  • 1
  • 1
Flip
  • 4,778
  • 1
  • 34
  • 48
  • Am I understanding correctly that I cannot bind the parameter like `SELECT :field FROM :table` and `setParameters(array('field' => 'id','table' => 'User'));`? – Gottlieb Notschnabel Aug 16 '13 at 12:56
  • Great, thanks. I modified your answer because I had to read twice to understand it. Thus I prefixed it with the "elevatorpitch answer". – Gottlieb Notschnabel Aug 16 '13 at 13:45
  • Is it more safe to use single quotation marks (`'SELECT x FROM '.$mapping...`) than double quotation marks (`"SELECT x FROM ".$mapping...` or even `"SELECT x FROM $mapping..."`)? – Gottlieb Notschnabel Aug 16 '13 at 13:46
  • 1
    This is only important for the clarity of your code, it doesn't affect security. To secure this properly you could for example check with `in_array` if the variable matches one of the allowed entities. – Flip Aug 16 '13 at 13:55