views:

25

answers:

3

Hi,

I know this sounds rediculously easy but there is simply no documentation about this subject findable on google.

I'd like to to select two columns from the database. I made a Zend_Db_Table object and point it to my table.

Now I like to select two columns: customerId and name.

What should I do to select just those two columns and not the whole table?

Thanks in advance, I'll bake you a cake or clean your room.

+3  A: 
$table->fetchAll(
    $table->select()
          ->from('table', array('column1', 'column2'))
);

And thanks, I already have a maid ;)

DASPRiD
Thanks! ;) I guess I'll send the cake by mail then.
baklap
You were faster :)
Richard Knop
A: 
$select = $db->select()
             ->from(array('t' => 'table'),
                    array('column1', 'column2'));
$stmt = $db->query($select);
$result = $stmt->fetchAll();
Richard Knop
A: 
$select = $db->select()
             ->from('products',
                    array('product_id', 'product_name', 'price'));

you have to pass the desired fiels as the second argument to the from() method, the first is the table. i know its a bit confusing because in regular sql syntax the desired fields go first, but zend db comes in quite handy if you want to custruct queries a modular way. array of strings and single string is accepted

another example:

Example #11 Examples of adding columns with the columns() method
// Build this query:
//   SELECT p."product_id", p."product_name"
//   FROM "products" AS p

$select = $db->select()
             ->from(array('p' => 'products'), 'product_id')
             ->columns('product_name');

// Build the same query, specifying correlation names:
//   SELECT p."product_id", p."product_name"
//   FROM "products" AS p

$select = $db->select()
             ->from(array('p' => 'products'), 'p.product_id')
             ->columns('product_name', 'p');
             // Alternatively use columns('p.product_name')
Joe Hopfgartner