0

My database (mysql) tables use TIMESTAMP columns, and whenever I want them returned in a query, I want them to be queried as "UNIX_TIMESTAMP(columnname)".

How do you easily modify queries in zend framework to achieve this?

For example, the current code is:

select = $this->select();
$select->where('user_id = ?',$user_id);
return $this->fetchAll($select);

This eventually becomes:

select * from tablename where user_id = 42;

I want something that automatically finds the TIMESTAMP column and changes the resulting query to:

select user_id,name,unix_timestamp(created) where user_id = 42;

I know I can use a MySQL view to achieve this, but I'd rather avoid that.

Thanks.

RR

1 Answer 1

2

You should be able to specify the fields you want in the select using the $select->from() object.

Zend_Db_Select

You should end up with something like this.

$select = $this->select();

$select->from(
    array('t' => 'tablename'),
    array('user_id', 'name', 'UNIX_TIMESTAMP(created)')
);

$select->where('user_id = ?',$user_id);
return $this->fetchAll($select);

If you wanted to run an expression that doesn't have parenthese in the function, Use the Zend_Db_Expr() method to escape the query properly.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your response. Yes, that's obvious. What I'm looking for is a way to do this without specifying all the columns. I want a generic solution that doesn't require me to maintain the list of columns in the PHP code for every table that has a timestamp.
Ahhh. Sorry I misunderstood. I'd recommend looking at something like Doctrine2 then. That will map your PHP classes to MySQL using annotations. It will generate the correct queries depending on how you have annotated the field. Doctrine2 ORM supports mapping between the TIMESTAMP MySQL type and PHPs DateTime automatically. It's probably overkill for want you are wanting, but it does make life easier once you get the hang of it. docs.doctrine-project.org/projects/doctrine-orm/en/latest/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.