active recored where statement - php

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.

Related

Yii2 - how to get a current quarter without the past quarter?

I've a problem here. I need to get a quarter of the year without the past quarter. F.e:
In my database I have a field created_at, which saves the timestamp of service created. I need to not involve those services, which was made in the past quarter. How should I do that?
I'm trying to write a SQL function like this to not involve those services, which was made in the past quarter:
$services= Service::find()
->where([
'client_service.created' => function ($model) {
return ceil(date('n') / 3) - 4;
But I guess I'm wrong. Thanks for any help.
Edited:
$services= Service::find()
->select(['client.id as client_id'])
->joinWith('client')
->where([
'service.type' => Service::TYPE,
'service.is_archived' => Service::ARCHIVED,])
->andWhere([
'or',
['client_service.status' => ClientService::STATUS_NEGATIVE],
[client_service.created' => function ($model) {
return ceil(date('n') / 3) - 4;]
You are storing timestemp in db for service date , we can find current Quarter start date and end date from current month and use in query.
$current_month = date('m');
$current_year = date('Y');
if($current_month>=1 && $current_month<=3)
{
$start_date = strtotime($current_year.'-01-01 00:00:00');
$end_date = strtotime($current_year.'-03-31 23:59:59');
}
else if($current_month>=4 && $current_month<=6)
{
$start_date = strtotime($current_year.'-04-01 00:00:00');
$end_date = strtotime($current_year.'-06-30 23:59:59');
}
else if($current_month>=7 && $current_month<=9)
{
$start_date = strtotime($current_year.'-07-01 00:00:00');
$end_date = strtotime($current_year.'-09-30 23:59:59');
}
else if($current_month>=10 && $current_month<=12)
{
$start_date = strtotime($current_year.'-10-01 00:00:00');
$end_date = strtotime($current_year.'-12-31 23:59:59');
}
Use this $start_date and $end_date timestemp in Query as below :
$services= Service::find()
->select(['client.id as client_id'])
->joinWith('client')
->where([
'service.type' => Service::TYPE,
'service.is_archived' => Service::ARCHIVED,])
->andWhere([
'or',
['client_service.status' => ClientService::STATUS_NEGATIVE],
['between', 'client_service.created', $start_date, $end_date]
])
Find start and end date of quarter
$date = new \DateTime(); // Current Date and Time
$quarter_start = clone($date);
// Find the offset of months
$months_offset = ($date->format('m') - 1) % 3;
// Modify quarter date
$quarter_start->modify(" - " . $months_offset . " month")->modify("first day of this month");
$quarter_end = clone($quarter_start);
$quarter_end->modify("+ 3 month");
$startDate = $quarter_start->format('Y-m-d');
$endDate = $quarter_end->format('Y-m-d');
Query
$services= Service::find()
->select(['client.id as client_id'])
->joinWith('client')
->where([
'service.type' => Service::TYPE,
'service.is_archived' => Service::ARCHIVED,])
->andWhere([
'or',
['client_service.status' => ClientService::STATUS_NEGATIVE],
['between', 'date_format(FROM_UNIXTIME(client_service.created), "%Y-%m-%d")', $startDate, $endDate]
You can also use mysql Quarter() to achieve the result.

"andWhere" clause doesn't work Doctrine2

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();

Add value (Array) in database

I tried this code but it does not work for me. i just want to add the array value to database. it give me error like this
Notice: Undefined offset: 2
Here is my code:
$timeadd = date("m-d-Y H:i:s", strtotime('+6 hours'));
$extinvoice=mysqli_query($link,"Select * from invoice WHERE BRANCH_CODE_MX='".$display_branchcode."' and INVOICE_NO_MX='".$invoicecode."' and INVOICE_ITEM_UNIT_MX='EXTENDEDWARRANTY'");
while($extrow=mysqli_fetch_array($extinvoice))
{
$ewtitemcode=$extrow["INVOICE_ITEM_CODE_MX"];
$imeiserialunit=$extrow["EWT_IMEI_MX"];
$customercode=$extrow["INVOICE_CUS_CODE_MX"];
$ewtarray[] = "('$invoicecode','$ewtitemcode', '$imeiserialunit','$customercode','$display_branchcode','$timeadd')";
}
$arrayitem=count($ewtarray);
for($item = 0; $item <= $arrayitem; $item++)
{
$sql = mysqli_query($link,"INSERT INTO extended_warranty
(INVOICE_NO_MX,FORM_EW_MX,EW_SERIAL_MX,CUSTOMER_CODE,BRANCH_CODE_MX,DATE_ADDED)
VALUES
($ewtarray[$item])");
}
The database requires a datatime in the format
2016-10-02 10:00:00
So change this
$timeadd = date("m-d-Y H:i:s", strtotime('+6 hours'));
to
$timeadd = date("Y-m-d H:i:s", strtotime('+6 hours'));
Additionally to the other users I have removed the double brackets. What happens now?
$timeadd = date("Y-m-d H:i:s", strtotime('+6 hours'));
$extinvoice=mysqli_query($link,"Select * from invoice WHERE BRANCH_CODE_MX='".$display_branchcode."' and INVOICE_NO_MX='".$invoicecode."' and INVOICE_ITEM_UNIT_MX='EXTENDEDWARRANTY'");
while ($extrow=mysqli_fetch_array($extinvoice)) {
$ewtitemcode=$extrow["INVOICE_ITEM_CODE_MX"];
$imeiserialunit=$extrow["EWT_IMEI_MX"];
$customercode=$extrow["INVOICE_CUS_CODE_MX"];
$ewtarray[] = "('$invoicecode','$ewtitemcode', '$imeiserialunit','$customercode','$display_branchcode','$timeadd')";
}
for ($item = 0; $item < count($ewtarray); $item++) {
$sql = mysqli_query($link,"INSERT INTO extended_warranty
(INVOICE_NO_MX,FORM_EW_MX,EW_SERIAL_MX,CUSTOMER_CODE,BRANCH_CODE_MX,DATE_ADDED)
VALUES
$ewtarray[$item]");
}

how to get query in symfony2?

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.

comparing date and time php

i need to compare two dates where if one date is greater than the other then an sql will run. this is my code
date_default_timezone_set('Asia/Kuala_Lumpur');
$date = date('Y-m-d G:i:s');
$query = mysql_query("SELECT * FROM package_transaction");
if(mysql_num_rows($query) > 0) {
while($row = mysql_fetch_array($query)) {
$transac_code = $row['transac_code'];
$duedate = $row['payment_due'];
if(strtotime($date) > strtotime($duedate))
{
mysql_query("UPDATE package_transaction SET `status` = 'cancelled' WHERE `payment_due` = `$duedate` AND `transac_code` = `$transac_code`");
}
}
}
but its not working. please help
try this,
date("Y-m-d", strtotime($date)) > date("Y-m-d", strtotime($duedate))
could you try and use the date format before using strtotime
$duedate = $row['payment_due'];
$duedate = $duedate->format('Y-m-d G:i:s');

Categories