0

I'm trying to write a simple method to sort some DB results. We are stuck using PEAR DB, which is an old OO data object class.

I need to dynamically set which column we sort by:

$query = $db->prepare('SELECT * FROM ' . $this->table . ' WHERE ? IS NOT NULL');

The problem occurs because when the statement is executed, I wind up with the column name in regular quotes instead of slanted ones, so in the example, the column is never NULL.

tadman
  • 208,517
  • 23
  • 234
  • 262
erfling
  • 384
  • 2
  • 16
  • bounce it against a list of known good column names... `in_array` – Orangepill May 15 '13 at 20:56
  • You mean "table name", not "column name", right? – tadman May 15 '13 at 20:58
  • Do you then have a bind statement? – Pitchinnate May 15 '13 at 21:03
  • No, I actually mean column name. This example is in a generic DAO class, and all our data classes extend it. $this->table is a property of whatever child class we are in, and is set to the table corresponding to a given class. Thanks, Orangepill. That just might work, especially since each class already has an array of the columns as a property. – erfling May 15 '13 at 21:05

1 Answers1

1

try something like this, it will bump the requested column up against a list of known good column.

 $columns = array("id", "name", "zipcode");
 if (!in_array($requestedCol, $columns)){
     // either reset $requestedCol to a default or error
 }
 $query = $db->prepare('SELECT * FROM ' . $this->table . ' WHERE '.$requestedColumn.' IS NOT NULL');
Orangepill
  • 24,500
  • 3
  • 42
  • 63
  • You are 100% correct. See my comment above. In addition to a $table property, each data class already has a $columns property so this is a perfect 5 second solution for me. – erfling May 15 '13 at 21:06