zf2 db sql where datetime before two ours ago - mysql

I'm looking for the right zf2 syntax to select timestamps / timeranges from the database. I know how to make where statements. However it seems that greaterThan() and lessThan() are not working with timestamps/datetime:
where = new Where();
$where->lessThan("datecolumn",$vardate);
I want to select all records older than 2 hours. so whats the right way to select date with zend framework 2?
Thx, I really appreciate your help

This works fine (just a sample) -
$select = new Select('album');
$created = date('Y-m-d H:i:s', strtotime("-2 hours"));
$where = new Where();
$where->lessThanOrEqualTo('created', $created);
$select->where($where);
$resultSet = $this->tableGateway->selectWith($select);

Try something like this in your mapper method:
$selectRecords = $this->tableGateway->getSql()->select();
$selectRecords->columns(array('id'))
->where->greaterThanOrEqualTo('dateColumn', $startDate)
->lessThanOrEqualTo('dateColumn', $endDate)
;
$resultSet = $this->tableGateway->selectWith($selectRecords);

Related

how to convert sql command to yii2

select g_code
from t_graph_name
where character_length(g_code) = 5
You need to read about build Query in Yii2..also you can read about active record too.
after reading it, you can see you can build it by Query builder like this:
$rows = (new \yii\db\Query())
->select(['g_code'])
->from('t_graph_name')
->where('character_length(g_code) = 5')
->all();

Joomla Development Database Select Query Giving Not unique table/alias

I'm developing a Joomla 3 component and I'm trying to select data from database using the Joomla framework classes. I'm getting a error Not unique table/alias. What could be the reason ?.
Code Snippet...
$app = JFactory::getApplication();
$job_id = JRequest::getVar('Jobid', null);
try {
$db = JFactory::getDbo();
$query = $db->getQuery(true);//Here Was The Problem
$query->select(array('A.state AS approval_state', 'A.*', 'B.*', 'C.district_name', 'D.educational_qualification', 'E.current_job_status'))
->from($db->quoteName('#__pes_job_provider_request_cv_info') . 'AS A')
->join('LEFT', '#__pes_jobseeker_profile AS B ON B.jobseeker_profile_id = A.jobseeker_profile_id')
->join('LEFT', '#__pes_district AS C ON C.district_id = A.district_id')
->join('LEFT', '#__pes_highest_educational_qualification AS D ON D.highest_educational_qualification_id = B.highest_educational_qualification_id')
->join('LEFT', '#__pes_current_job_status AS E ON E.current_job_status_id = B.current_job_status_id')
->where($db->quoteName('A.job_order_registration_id') . ' = ' . $db->quote($job_id))
->order('B.name_in_full ASC');
$db->setQuery($query);
$results = $db->loadObjectList();
Thank You.
OK ! I figured out the reason.
The reason why this happened is that I haven't instantiated the query object as a new query.
i.e. $query = $db->getQuery();
So, in order to resolve the issue I simply gave the parameter boolean true for the query method
i.e. $query = $db->getQuery(true);

Get only records created today in laravel

How do I use the created_at field to get only the records that were created today and no other day or time?
I was thinking of a ->where('created_at', '>=', Carbon::now()) But Im not sure that would work.
For Laravel 5.6+ users, you can just do
$posts = Post::whereDate('created_at', Carbon::today())->get();
Use Mysql default CURDATE function to get all the records of the day.
$records = DB::table('users')->select(DB::raw('*'))
->whereRaw('Date(created_at) = CURDATE()')->get();
dd($record);
Note
The difference between Carbon::now vs Carbon::today is just time.
e.g
Date printed through Carbon::now will look like something:
2018-06-26 07:39:10.804786 UTC (+00:00)
While with Carbon::today:
2018-06-26 00:00:00.0 UTC (+00:00)
To get the only records created today with now can be fetched as:
Post::whereDate('created_at', Carbon::now()->format('m/d/Y'))->get();
while with today:
Post::whereDate('created_at', Carbon::today())->get();
UPDATE
As of laravel 5.3, We have default where clause
whereDate / whereMonth / whereDay / whereYear
$users = User::whereDate('created_at', DB::raw('CURDATE()'))->get();
OR with DB facade
$users = DB::table('users')->whereDate('created_at', DB::raw('CURDATE()'))->get();
Usage of the above listed where clauses
$users = User::whereMonth('created_at', date('m'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->month;
//select * from `users` where month(`created_at`) = "04"
$users = User::whereDay('created_at', date('d'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->day;
//select * from `users` where day(`created_at`) = "03"
$users = User::whereYear('created_at', date('Y'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->year;
//select * from `users` where year(`created_at`) = "2017"
Query Builder Docs
If you are using Carbon (and you should, it's awesome!) with Laravel, you can simply do the following:
->where('created_at', '>=', Carbon::today())
Besides now() and today(), you can also use yesterday() and tomorrow() and then use the following:
startOfDay()/endOfDay()
startOfWeek()/endOfWeek()
startOfMonth()/endOfMonth()
startOfYear()/endOfYear()
startOfDecade()/endOfDecade()
startOfCentury()/endOfCentury()
with carbon:
return $model->where('created_at', '>=', \Carbon::today()->toDateString());
without carbon:
return $model->where('created_at', '>=', date('Y-m-d').' 00:00:00');
You can use
whereRaw('date(created_at) = curdate()')
if the timezone is not a concern or
whereRaw('date(created_at) = ?', [Carbon::now()->format('Y-m-d')] )
otherwise.
Since the created_at field is a timestamp, you need to get only the date part of it and ignore the time part.
Laravel ^5.6 - Query Scopes
For readability purposes i use query scope, makes my code more declarative.
scope query
namespace App\Models;
use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
// ...
/**
* Scope a query to only include today's entries.
*
* #param \Illuminate\Database\Eloquent\Builder $query
* #return \Illuminate\Database\Eloquent\Builder
*/
public function scopeCreatedToday($query)
{
return $query->where('created_at', '>=', Carbon::today());
}
// ...
}
example of usage
MyModel::createdToday()->get()
SQL generated
Sql : select * from "my_models" where "created_at" >= ?
Bindings : ["2019-10-22T00:00:00.000000Z"]
$today = Carbon\Carbon::now()->format('Y-m-d').'%';
->where('created_at', 'like', $today);
Hope it will help you
No need to use Carbon::today because laravel uses function now() instead as a helper function
So to get any records that have been created today you can use the below code:
Model::whereDay('created_at', now()->day)->get();
You need to use whereDate so created_at will be converted to date.
simple solution:
->where('created_at', 'like', date("Y-m-d")."%");
I’ve seen people doing it with raw queries, like this:
$q->where(DB::raw("DATE(created_at) = '".date('Y-m-d')."'"));
Or without raw queries by datetime, like this:
$q->where('created_at', '>=', date('Y-m-d').' 00:00:00'));
Luckily, Laravel Query Builder offers a more Eloquent solution:
$q->whereDate('created_at', '=', date('Y-m-d'));
Or, of course, instead of PHP date() you can use Carbon:
$q->whereDate('created_at', '=', Carbon::today()->toDateString());
It’s not only whereDate. There are three more useful functions to filter out dates:
$q->whereDay('created_at', '=', date('d'));
$q->whereMonth('created_at', '=', date('m'));
$q->whereYear('created_at', '=', date('Y'));
Below code worked for me
$today_start = Carbon::now()->format('Y-m-d 00:00:00');
$today_end = Carbon::now()->format('Y-m-d 23:59:59');
$start_activity = MarketingActivity::whereBetween('created_at', [$today_start, $today_end])
->orderBy('id', 'ASC')->limit(1)->get();
Carbon::today() will return something like this: 2021-08-06T00:00:00.000000Z, so using Model::where('created_at', Carbon::today()) will only return records created at exactly 12:00 am current date.
Use Model::where('created_at', '>=', Carbon::today()) instead
Post::whereDate('created_at', '=', date('Y-m-d'))->get();
It will give you All the posts created today !!!!! if you use time with this you will get posts of that particular time not of today
laravel 8
$VisitorEntryStatusDateCurrent = VisitorEntry::whereDate('created_at', Carbon::today())->get();
$records = User::where('created_at' = CURDATE())->GET());
print($records);
I use laravel9 on 22 Apr 2022
how I get the "today" record is :
I have edit "config/app.php" on the "timezone" (about line 72 ) I have set it to my timezone which is "Asia/Bangkok"
my query code I have is :
$get = User::whereDate("created_at","=",date("Y-m-d",time() ) )->get();
will get the field that created today.
I don't know if this a correct way or it another bad code but as long as it work for me I will be okay.

Joomla Database - How to use LIMIT in getQuery?

I want to build the below query using joomla inbuilt database class.
SELECT *
FROM table_name
ORDER BY id DESC
LIMIT 1
This is the query I have built up to now.
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->select($db->nameQuote('*'));
$query->from($db->nameQuote(TABLE_PREFIX.'table_name'));
$db->setQuery($query);
$rows = $db->loadObjectList();
I don't know how to add the limit(LIMIT 1) to the query. Can someone please tell me how to do it? Thanks
Older than Joomla 3.0
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select('*')
->from($db->nameQuote('#__table_name'))
->order($db->nameQuote('id').' desc');
$db->setQuery($query,0,1);
$rows = $db->loadObjectList();
$db->setQuery function takes 3 parameters. The first one being the query, then the start, then the limit. We can limit records as shown above.
Newer than Joomla 3.0
setLimit(integer $limit, integer $offset)
If you want just one row
$query->setLimit(1);
Read more
This should work as well:
$query->setLimit(1);
Documentation: http://api.joomla.org/cms-3/classes/JDatabaseQueryLimitable.html
SetLimit doesn't work for me in Joomla 3.4.x, so try:
Within the model:
protected function getListQuery()
{
// Create a new query object.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Select some fields
$query->select('*');
$query->from('#__your_table');
$this->setState('list.limit', 0); // 0 = unlimited
return $query;
}
Davids answer: https://joomla.stackexchange.com/questions/4249/model-getlistquery-fetch-all-rows-with-using-jpagination
Run that before the model calls getItems and it will load all the
items for you.
A few caveats with this.
You can also do this outside the model, so if for instance you were in
your view. You could do the following:
$model = $this->getModel(); $model->setState('list.limit', 0);
Sometimes you can do this too early, before the model's state has been
populated, which will cause the model to get rebuilt from the user
state after you have set the limit, basically overriding the limit.
To fix this, you can force the model to populate its state first:
$model = $this->getModel(); $model->getState();
$model->setState('list.limit', 0); The actual populateState method is
protected, so outside the model you can't call it directly, but any
call to getState will make sure that the populateState is called
before returning the current settings in the state.
Update: Just had to revisit this answer, and I can confirm, both the methods
setLimit & order are working if used as below.
$query->order($db->qn($data->sort_column_name) . ' ' . $data->sort_column_order);
$query->setLimit($length,$start);
OLD ANSWER
As of 08/Sept/14 The solutions from #Dasun or #escopecz arent working for me on J3.x
but this old trick is working for me which is nice,
$query->order($db->qn('id') . ' DESC LIMIT 25');
And About your specific requirement of wishing to fetch only 1 row you could use :
$rows = $db->loadObject();

Troubles with IN in Yii query builder

I use Yii Framework and i need to build difficult query with many conditions.
I'm filling 2 arrays $conditions and $values.
And i have one problem.
Below is example
When i use
$usersId = '1,2';
$conditions[] = 'e.user_id IN(:usersId)';
$values[':usersId'] = $usersId;
I get only value from user_id = 1
When i'm not use option and write manually
$usersId = '1,2';
$conditions[] = 'e.user_id IN(' . $usersId . ')';
no problem.
Of course i can use second construction, but it seems not very good.
You should addInCondition
$criteria->addInCondition('e.user_id',array(1,2));
Yii way would be to use CDbCriteria addInCondition function
$usersId = array(1,2); //must be array
$criteria=new CDbCriteria();
$criteria->addInCondition('user_id',$usersId);
$result = MyModel::model()->findAll($criteria);
$values[':usersId'] = $usersId;
If I understand your wuestion correctly, you can use the BindParam function in yii?
Instead of this - $values[':usersId'] = $usersId;
Write this - $command->BindParam(':usersId', $usersId, PDO::PARAM_STR);
Very simply, you're binding your parameters to your command statement.
Hope it works!