Between operator not working in mysql - php

In mysql how to get the sum between 2 dates.
In my query I'm getting the days between the same months(01-01-2016 to 31-01-2016) But I'm not getting 2 different months (01-01-2016 to 06-02-2016) the result is returns null value.
select sum(cash),sum(advnce)
from tablename where date
between '$strt_dte' and '$srch_prev_date'
GROUP by date

Give the following a go. Make sure your dates are formatted correctly!
$strt_dte = '2016-01-01';
$srch_prev_date = '2016-01-31';
$sql = "
SELECT SUM(cash), SUM(advnce)
FROM tablename
WHERE date BETWEEN '{$strt_dte}' AND '{$srch_prev_date}'
GROUP BY date
";

Related

How to fetch record by month in MySQL?

I have stored Date in database in dd-mm-yy format, for example 03-10-2013,
How to search record by month? Month in digit (01 to 12);
I am using currently
$query = "SELECT * FROM data WHERE date LIKE %$month%";
but this not working properly.
I am assuming when you say dates as stored in the database in a format, that they are not stored using a "date" type and instead are using a varchar or char type for the column.
Based on that there are few ways to do this.
Leave the database as it is and convert values on the fly.
SELECT * FROM data WHERE Month(STR_TO_DATE(datestrcolumn, '%d/%m/%Y')) = 5;
Change the type of the column to a "date" type column
SELECT * FROM data WHERE Month(realdatecolumn) = 5;
Change the type of the column to a "date" type column, store a separate column for the month.
UPDATE data set monthcolumn = Month(realdatetimecolumn)
then
SELECT * FROM data WHERE monthcolumn = 5;
Create an index on monthcolumn and this query will be much faster than the other queries if there is a lot of data
Fix the date format in your database structure first, change it to: yyyy-mm-dd
Then change your query statement to:
$query = "SELECT * FROM data WHERE MONTH(`date`) = '$month';
This will select the month as '5' or '11' or '12' which will give duplicates for differing years.
If you need the month with year (to avoid duplicate years):
$query = "SELECT * FROM data WHERE SUBSTR(DATE(`date`),1,7) = SUBSTR(DATE('$month'),1,7);
This will return: '2015-01' or '2014-12'
To get date as '01' or '04' or '12':
$query = "SELECT * FROM data WHERE SUBSTR(DATE(`date`),6,2) = SUBSTR(DATE('$month'),6,2);
Try this...
You could use MySQL MONTH() function
MySQL MONTH() returns the MONTH for the date within a range of 1 to 12 ( January to December). It Returns 0 when MONTH part for the date is 0
4 is april
SELECT * FROM tbl WHERE MONTH( date ) ='4'
You can do like it... as it is not in date format(YYYY-MM-DD)
$q="SELECT * FROM data WHERE MONTH(DATE_FORMAT(STR_TO_DATE(date, '%d-%m-%Y'), '%Y-%m-%d') ) = '$YOUR_SEARCH_MONTH' ";

convert Unix Time stamp and sort data in mysql query

I am trying to query a small database by date, my date table data is stored in time 2014-02-04 . how can I convert that and check it against todays date.
This is what I have but I am getting a few errors
$q = 'SELECT count(*) as count FROM SHOW WHERE date('Y-m-d', strtotime
('SHOW_DATE') ='.$db->qstr(date()).' AND CONTACT='.$db->qstr($name);
if(!$rs = $db->execute($q)){
force_page('core', 'error&error_msg=MySQL Error: '.$db->ErrorMsg().'&menu=1');
exit;
} else {
$today_count = $rs->fields['count'];
$smarty->assign('today_count',$today_count);
}
Thanks a lot.
You can convert show_date to a date format using FROM_UNIXTIME function. And then compare the date part of it with your input date value.
Example:
SELECT count(*) as count FROM `SHOW`
WHERE date( from_unixtime( `SHOW_DATE` ) ) = ? AND CONTACT=?
Use prepared statement to bind input values to the place holders.
To find a row containing a DATE matching the current date, use CURDATE():
SELECT column FROM table WHERE col_date = CURDATE()

How to use current date in mysql query?

I have a database that contains a column with type - Date. I also have a query with the date inputted as static which works fine but I would like to use todays date in the query. any recommendations?
Query :
$q = 'SELECT count(ID) as count FROM ORDER WHERE
ASSIGN_TO ='.$db->qstr($person).' AND OPEN_DATE ='.$db->qstr('2014-05-14');
This currently displays count of items after 2014-05-14
You could use the NOW() function that returns the current date. To avoid skewed answered by hours/minutes/seconds, you can use date to extract the date part:
$q = 'SELECT count(ID) as count FROM ORDER WHERE
ASSIGN_TO ='.$db->qstr($person).' AND DATE(OPEN_DATE) = DATE(NOW())';

Getting the data for each month

So what I want to do is basically this:
Month and Year:
-All the data sent on that month and year
For example:
February 2013:
-The posts on this date
March 2013:
-The posts on this date
and so on.
I have a date column on my table and it has the following format: day.month.year
I am using PHP and MySQL.
I have my own MVC framework that I'm using. I will simplify it to make it more understanble here. The function to fetch data:
function selectAll($sql){
$find = $this->prepare($sql);
$find->execute();
$fetchdata = $find->fetchAll(PDO::FETCH_ASSOC);
return $fetchdata;
}
And the code to get the dates :
$sql = "Select YEAR(Date) AS year, MONTH(Date) AS month, Headline from blog";
$data = $this->db->selectAll($sql);
foreach($data as $key => $value) {
$date[] = $value['month'].'.'.$value['year'];
}
$dateunique = array_unique($date);
This give me the results for the dates but I cannot figure out how to put the correct data under each date.
Convert the varchar date field into exact date using
str_to_date function
Using DATE_FORMAT you can select month wise record
Where $input is %Y-%m format // ex: 02-2013-> feb 2013
SELECT * FROM `table`
WHERE DATE_FORMAT(str_to_date(`date_column`, '%d/%m/%Y'), '%Y-%m')= '".$input."';
Use DATE_FORMAT mysql function.
Example
SELECT DATE_FORMAT(date_field,'%M') as Month,DATE_FORMAT(date_field,'%Y') as Year FROM table_name
and then debug result of query you will see two extra column for month and year then display it as your desire.
if date_field is varchar then use str_to_date mysql function.
SELECT STR_TO_DATE(date_field,'%M') as Month, STR_TO_DATE(date_field,'%Y') as Year FROM table_name;
OP question update
Try GROUP_CONCAT
SELECT
*,
GROUP_CONCAT(created) AS month
FROM
table_name
GROUP BY MONTH(created) DESC;

MySQL & PHP: summing up data from a table

Okay guys, this probably has an easy answer but has been stumping me for a few hours now.
I am using PHP/HTML to generate a table from a MySQL Table. In the MySQL table (TimeRecords) I have a StartTime and EndTime column. In my SELECT statement I am subtracting the EndTime from the StartTime and aliasing that as TotalHours. Here is my query thus far:
$query = "SELECT *,((EndTime - StartTime)/3600) AS TotalPeriodHours
FROM TimeRecords
WHERE Date
BETWEEN '{$CurrentYear}-{$CurrentMonth}-1'
AND '{$CurrentYear}-{$CurrentMonth}-31'
ORDER BY Date
";
I then loop that through an HTML table. So far so good. What I would like to do is to add up all of the TotalHours and put that into a separate DIV. Any ideas on 1) how to write the select statement and 2) where to call that code from the PHP/HTML?
Thanks in advance!
Try this
$query= "
SELECT ((EndTime - StartTime)/3600) AS Hours, otherFields, ...
FROM TimeRecords
WHERE
Date BETWEEN '{$CurrentYear} - {$CurrentMonth} - 1'
AND '{$CurrentYear}-{$CurrentMonth} - 31' ";
$records =mysql_query($query);
$sum= 0;
while($row=mysql_fetch_array($records))
{
echo"$row['otherFields']";
echo"$row['Hours']";
$sum+=$row['Hours'];
}
echo" Total Hours : $sum ";
Just use a single query with a Sum(). You could also manually calculate it if you're already displaying all rows. (If paginating or using LIMIT, you'll need a separate query like below.)
$query = "
SELECT Sum(((EndTime - StartTime)/3600)) AS SumTotalPeriodHours
FROM TimeRecords
WHERE
Date BETWEEN '{$CurrentYear} - {$CurrentMonth} - 1'
AND '{$CurrentYear}-{$CurrentMonth} - 31'
";
You can do this in the same query if you have a unique id using GROUP BY WITH ROLLUP
$query = "
SELECT unique_id,SUM((EndTime - StartTime)/3600) AS TotalPeriodHours
FROM TimeRecords
WHERE Date BETWEEN '{$CurrentYear}-{$CurrentMonth}-1'
AND '{$CurrentYear}-{$CurrentMonth}-31'
GROUP BY unique_id WITH ROLLUP
ORDER BY Date
";
In this instance the last result from your query with contain NULL and the overall total. If you don't have a unique ID you will need to do it in PHP as per Naveen's answer.
A few comments on your code:
Using SELECT * is not considered good practice. SELECT the columns you need.
Not all months have a day 31 so this may produce unexpected results. If you're using PHP5.3+, you can use
$date = new DateTime();
$endDate = $date->format( 'Y-m-t' );
The "t" flag here gets the last day of that month. See PHP docs for more on DateTime.

Categories