I'm creating a query like this
$om = $this->getContainer()->get('doctrine')->getManager();
$qb = $om->createQueryBuilder()
->from('ProbusQuoteExtraBundle:Quote', 'q')
->select('q', 'b')
->join('q.booking', 'b')
->orderBy('q.id', 'asc')
->where("q.startDate >= '" . date('Y-m-d H:i:s', strtotime('-1 hour')) . "'")
->andWhere("q.startDate <= '" . date('Y-m-d H:i:s', time()) . "'")
;
i want to check if i created correct query or not by using this
echo $qb->getQuery();
but it gives error.
If you want to check your statement in DQL or SQL you can do this by
calling ->getSQL(), or ->getDQL() on $qb->getQuery();
Also I recommend installing xdebug and using var_dump():
$sql = $qb->getQuery()->getSQL();
$dql = $qb->getQuery()->getDQL();
var_dump($sql);
var_dump($dql);
It will print both, a SQL and DQL dump of your QueryBuilder
And since we're at it, instead of injecting your parameters by concatenation use the QueryBuilders ->setParameters() method:
->where("q.startDate >= :startDate")
->andWhere("q.startDate <= :endDate")
->setParameters(array(
'startDate' => date('Y-m-d H:i:s', strtotime('-1 hour')),
'endDate' => date('Y-m-d H:i:s', time()),
))
You can find more on that in the Doctrine2 documentation.
Related
I want to create a function that checks, if a specific time is between two timestamps that are stored in a MySQL database.
The function should be able to ignore the time ($fullday = true) or check the time as well.
My presence table has a row with start = 2021-11-01 10:00:00 and end = 2021-11-05 18:00:00.
is_available('2021-11-02', true); should give me a result, but is doesn't.
What I expect as well:
is_available('2021-11-01 09:30:00'); should not have a result, as 9:30 is before 10:00 but is_available('2021-11-01 10:01:00'); should give me a result. And so on.
The query, my function creates is:
SELECT *
FROM `presence`
WHERE DATE_FORMAT(start, "%Y-%m-%d") <= "2021-11-02"
AND DATE_FORMAT(end, "%Y-%m-%d") >= "2021-11-02"
And this my function so far:
function is_available($date, $fullday = false)
{
$presenceModel = new PresenceModel();
if ($fullday) {
$date = date('Y-m-d', strtotime($date));
$presences = $presenceModel
->where('DATE_FORMAT(start, "%Y-%m-%d") <= "' . $date . '"')
->where('DATE_FORMAT(end, "%Y-%m-%d") >= "' . $date . '"')
->findAll();
} else {
$date = date('Y-m-d H:i:s', strtotime($date));
$presences = $presenceModel
->where('DATE_FORMAT(start, "%Y-%m-%d %H:%i:%s") <= "' . $date . '"')
->where('DATE_FORMAT(end, "%Y-%m-%d %H:%i:%s") >= "' . $date . '"')
->findAll();
}
return count($presences) > 0 ? true : false;
}
You should be able to simplify this dramatically by getting MySQl to do more of the work. You don't need to format DATETIME columns to do comparisons on them, and BETWEEN will further reduce your PHP effort.
Based on your code above I think this will do the job:
function is_available($date, $fullDay = false) {
$presenceModel = new PresenceModel();
$date = date('Y-m-d H:i:s', strtotime($date));
if ($fullDay) {
$presences = $presenceModel
->where("'$date' between DATE(`start`) and DATE(`end`)" )
->findAll();
} else {
$presences = $presenceModel
->where("'$date' between `start` and `end`" )
->findAll();
}
return count($presences) > 0 ? true : false;
}
However, using SELECT * will return the entirety of all the matching rows, when all you really need is whether one exists. You should aim to get your query something close to this, which will return just a single value (1) if there's a matching row.:
SELECT 1 FROM `presence`
WHERE "2021-11-02" between start AND end
LIMIT 1
My approach would be to use strtotime() function to convert the date into an int and then convert the other date from the db and then compare those ints in php.
if($datenow > $dbstartdate && $datenow < $dbenddate){
return true;
}else{
return false;
}
Hi I have one column name as date which will hold advance payment date. I want to fetch current month date advance paid. for what i am using below code.
echo $startDate = date($currentYear . "-" . $currentMonth . "-1");
echo $endDate = date($currentYear . "-" . $currentMonth . "-" . $numberOfDaysInMonth);
DB::enableQueryLog();
echo $advances = UserServiceAdvancePayment::where('user_service_master_id', $userServiceMasterObject->id)
->whereDate('date', ">=", $startDate)
->whereDate('date', "<", $endDate)
->get();
Herein am getting data when am applying one date condition but when applying other it is not returning data. Also tried with between there also same issue. Any help is deeply appreciated on this
If I understand what you need to do correctly then it's easier to use Carbon to do it:
$startDate = CarbonImmutable::createFromDate($currentYear, $currentMonth, 1)
$endDate = CarbonImmutable::createFromDate($currentYear, $currentMonth, 1)->endOfMonth();
DB::enableQueryLog();
$advances = UserServiceAdvancePayment::where('user_service_master_id', $userServiceMasterObject->id)
->whereDate('date', ">=", $startDate)
->whereDate('date', "<=", $endDate)
->get();
I want to get some data from database table, where date field is in range between two dates.
Here is my code below:
$date = new \DateTime('today');
$newDate = new \DateTime('today');
$newDate->add(new \DateInterval('P2D'));
$query = $repository->createQueryBuilder('s')
->select('s.day')
->where('s.day > :data')
->andWhere('s.day < :newDate')
->setParameter('data', $date)
->setParameter('newDate', $newDate)
->getQuery();
$dates = $query->getResult();
But unfortunately it doesn't work.
The second method gives empty array, too.
$date = new \DateTime('today');
$newDate = new \DateTime('today');
$newDate->add(new \DateInterval('P2D'));
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT s.day
FROM AppBundle:Seance s
WHERE s.day BETWEEN :date AND :newDate')
->setParameter('date', $date)
->setParameter('newDate', $newDate);
$seances= $query->getResult();
If I remove andWhere clause or between, doctrine returns data correctyly but all recordse
Does anyone have idea why it doesn't work?
In my application I do what you are asking, using the following:
/* #var $date1 \DateTime */
$date1 = \DateTime::createFromFormat('d/m/Y', $this->request()->get("from_date"));
$date1->format('Y-m-d h:i:s');
$date1->setTime(0, 0, 0); // You'll likely not need this bit if times don't matter to you
/* #var $date2 \DateTime */
$date2 = \DateTime::createFromFormat('d/m/Y', $this->request()->get("to_date"));
$date2->format('Y-m-d h:i:s');
$date2->setTime(23, 59, 59); // You'll likely not need this bit if times don't matter to you
Then in it's repository we do this:
->andWhere("s.date >= :date1 AND s.date < :date2)
You simply needed to pass correct criteria.
$dateFrom = (new \DateTime())->setTime(0, 0, 0);
$dateTo = (new \DateTime())->add(new \DateInterval('P2D'))->setTime(23, 59, 59);
$query = $repository->createQueryBuilder('s')
->where('s.day >= :dateFrom', 's.day <= :dateTo')
->setParameter('dateFrom', $dateFrom)
->setParameter('dateTo', $dateTo)
->getQuery();
$dates = $query->getResult();
In codeigniter I am trying to produce the following SQL statement:
SELECT *
FROM (`ea_users`,`ea_appointments`,`ea_services`)
WHERE `ea_appointments`.`id_users_customer` = `ea_users`.`id`
AND `ea_appointments`.`id_services` = `ea_services`.`id`
AND `ea_appointments`.`start_datetime`> '2015-07-18 00:00:00'
AND `ea_appointments`.`start_datetime`< '2015-07-18 23:59:59'
In the Active Record format I have tried this:
$day_start = date('Y-m-d 00:00:00', $day);
$day_end = date('Y-m-d 23:59:59', $day);
return $this->db->select('*')
->from('ea_appointments,ea_services,ea_users')
->where('ea_appointments.id_users_customer','ea_users.id')
->where('ea_appointments.id_services','ea_services.id')
->where('ea_appointments.start_datetime>',$day_start)
->where('ea_appointments.start_datetime<',$day_end)
->get()->result();
But it produces this instead:
SELECT *
FROM (`ea_appointments`, `ea_services`, `ea_users`)
WHERE `ea_appointments`.`id_users_customer` = 'ea_users.id'
AND `ea_appointments`.`id_services` = 'ea_services.id'
AND `ea_appointments`.`start_datetime>` '2015-07-18 00:00:00'
AND `ea_appointments`.`start_datetime<` '2015-07-18 23:59:59'
How do I get 'ea_users.id' and 'ea_services.id' to be translated as 'ea_users'.'id' and 'ea_services'.'id'? I have tried:
->where('ea_appointments.id_users_customer','ea_users'.'id')
->where('ea_appointments.id_services','ea_services'.'id')
But that produces this:
WHERE `ea_appointments`.`id_users_customer` = 'ea_usersid'
AND `ea_appointments`.`id_services` = 'ea_servicesid'
What is the correct format?
This should work:
(A space before the > < signs)
$day_start = date('Y-m-d 00:00:00', $day);
$day_end = date('Y-m-d 23:59:59', $day);
return $this->db->select('*')
->from('ea_appointments,ea_services,ea_users')
->where('ea_appointments.id_users_customer','ea_users.id')
->where('ea_appointments.id_services','ea_services.id')
->where('ea_appointments.start_datetime >',$day_start)
->where('ea_appointments.start_datetime <',$day_end)
->get()->result();
Assuming your original sql function works as you intended it before you tried to recreate it in codeigniter, You can simply do this.
$day_start = date('Y-m-d 00:00:00', $day);
$day_end = date('Y-m-d 23:59:59', $day);
$query = $this->db->query(SELECT *
FROM (ea_users, ea_appointments, ea_services)
WHERE ea_appointments.id_users_customer = ea_users.id
AND ea_appointments.id_services = ea_services.id
AND ea_appointments.start_datetime > {$day_start}
AND ea_appointments.start_datetime < {$day_end});
$query->result();
This worked:
$day_start = date('Y-m-d 00:00:00', $day);
$day_end = date('Y-m-d 23:59:59', $day);
return $this->db->select('ea_appointments.id,
ea_appointments.start_datetime,
ea_appointments.end_datetime,
ea_users.email,
ea_services.name')
->from('ea_appointments')
->join('ea_users', 'ea_appointments.id_users_customer = ea_users.id','left')
->join('ea_services', 'ea_appointments.id_services = ea_services.id','left')
->where('ea_appointments.start_datetime >',$day_start)
->where('ea_appointments.start_datetime <',$day_end)
->get()->result();
Join statements did the trick.
I have some events stored in a database using doctrine and Symfony2, and those events have a two datetime parameters, start and end of the event. I need to know if those events are active during a certain month, but i cant find a way. I tried with :
$now = new \Datetime('now');
$qb = $this->createQueryBuilder('e');
$qb->where('e.start <= :now AND e.end >= :now')
->setParameter('now', $now);
return $qb->getQuery()
->getArrayResult();
but it limits to the day, and not to the month. Is there a way to check it ? Thanks a lot !
You can use the following code
$monthStart = new DateTime(date('Y-m-01') . " 00:00:00");
$monthEnd = new DateTime(date('Y-m-t'). " 23:59:59");
$qb = $this->createQueryBuilder('e');
$qb
->where('e.start <= :end AND e.end >= :start')
->setParameter('start', $monthStart)
->setParameter('end', $monthEnd);
return $qb->getQuery()
->getArrayResult();