Embedded SQL request - php

I have a SQL Database. In here is a table called Reports and it looks like this
ID Date Year Title Links
1 2010-05-03 2010 Report 1 link1.php
2 2010-09-03 2010 Report 2 link2.php
3 2011-01-05 2011 Report 3 link3.php
What I'm trying to achieve it the this. I want to select all the reports of 2010-2011 but the ones from 2010 may only be those dating from september.
Right now, I've got a SQL statement selecting all the reports of the two years
$sql = "SELECT * FROM Reports WHERE Year = ".$db->escape($jaar1)." OR jaar = ".$db->escape($jaar2);
How can I select Report 2 (cause it dates from september 2010) and Report 3 (cause it dates from 2011)?

The easiest way as I see it, is to use the BETWEEN...AND operator.
SELECT *
FROM `Reports`
WHERE `Date` BETWEEN '2010-09-01' AND NOW()
Note the backticks. Especially important around Date, because it is a reserved word.

Assuming the Date column is of type DATE:
SELECT *
FROM `Reports`
WHERE (YEAR(`Date`) = 2010 AND MONTH(`Date`) = 9)
OR YEAR(`Date`) = 2011

general pattern
where year = 2011
or ( year = 2010 and month = 'September' )

Related

Issues with SQL - SELECT between two dates

I got this old system that I have to do maintenance in the place I work and they asked me to add a Date Filter on the system, but the date field is not only a field, the previous developer has split it in three, just like that "year_id", "month_id", "day_id"
And now I have to do a SELECT between the two dates (between the month and year to be more specific) and I tried just like that:
select
* from `table`
where
(
(`year_id` >= 2018 and `month_id` >= 10)
or
(`year_id` <= 2019 and `month_id` <= 3)
)
When I saw the results I realized that the query is also returning the results from Jan, Feb and Mar of 2018 and it is not supposed to do that.
How can I apply those filters?
The ideal thing you should do is add a new column
select
*,STR_TO_DATE(Concat(year_id,month_id),'%Y%m') as 'YearMonth' from `table`;
This would create a new column YearMonth and then you can use your filters
select * from (
select
*,STR_TO_DATE(Concat(year_id,month_id),'%Y%m') as 'YearMonth' from `table`
) z where (YearMonth between '201810' and '201903')
It should be possible to write a query that implements a date range filtering based on input parameters and on the existing columns. For example if you want records between October 2018 and March 2019 (inclusive), you could do:
(year_id = 2018 and month_id >= 10)
or (year_id = 2019 and month_id <= 3)
However the logic need to be adapted depending on the date range. For example if you want records between October 2017 and March 2019, then you need:
(year_id = 2017 and month_id >= 10)
or year_id = 2018
or (year_id = 2019 and month_id <= 3)
You can see that this does not scale well. For the sake of simplicity, I would suggest using str_to_date() to convert your strings to date, so you can do proper date comparison:
str_to_date(concat (year_id, '-', month_id), '%Y-%m') between '2017-10-01' and '2019-03-01'
You could add a computed column to your table that prepares the date value for you:
alter table mytable add
mydate date as (str_to_date(concat (year_id, '-', month_id), '%Y-%m'))
Thank everyone that answered && added comments, I just fixed the problem.
The solution posted by GMB worked well, you just saved me <3
I did like u suggested:
$data_inicial = Controller::toDate($data_inicial, 'm/Y', 'Y-m') . '-01';
$data_final = Controller::toDate($data_final, 'm/Y', 'Y-m') . '-01';
$query->whereBetween(DB::raw("STR_TO_DATE(CONCAT(sicc_ano_id, '-', sicc_mes_id), '%Y-%m')"), [$data_inicial, $data_final]);

Php, MySql select records within current year, month range

I'm trying to create a query to select records that fit current year month range. Here is my database table:
id name date_start date_end
======================================
1 John 2016-05-20 2018-01-01
2 Peter 2017-02-02 2017-05-10
3 Mike 2015-02-02 2017-02-06
and my query:
SELECT * FROM users
WHERE YEAR(date_start) = 2017
AND MONTH(date_start) = 01
OR YEAR(date_end) = 2017
AND MONTH(date_end) = 01
So basically I need to select all users where current year/month in this case 2017/01 is within start/end column range.
In above query, only John and Mike records should be selected.
I think you just want to find out which users have the date 2017-01-01 within their ranges, defined by the date_start and date_end. If so, then the following query should work:
SELECT *
FROM users
WHERE date_start <= '2017-01-01' AND date_end >= '2017-01-01'
Demo here:
SQLFiddle

Filter Dates in sql by months - php,sql

I have a table in sql and in that table I have column with the action date by this format: 2015-08-26 05:54:39
Now I built a system in php and i want to get all the actions that was in the same month.
I try to run that:
SELECT * FROM `Expenses` WHERE DateAction between '2015-08-01 00:00:00' and '2015-09-01 00:00:00'
and its return the actions dates that was in the same month, But its can return the the action that was in 2015-09-01 00:00:00 so i understand i need to get the last day in the month and put it in the sql query.
How I do that?
Right now this is the call to the sql:
$query = mysql_query("SELECT * FROM `Expenses` WHERE `accountid` = $accountId");
Fortunately for you, there's MySQL's MONTH() command.
https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_month
SELECT * FROM `Expenses` WHERE MONTH(DateAction) = 8;
//Selects all rows in the month "August"
All months are recorded numerically (1 is January, 2 is February,...... 12 is December). It will always be precise based on your database time and date settings.
If you want to customize your query further (selecting the same year and month), then you can read more about date commands here
SELECT * FROM `Expenses` WHERE Year(DateAction) = '2015' AND MONTH(DateAction) = '8';
//Selects all rows in year 2015 and month "August"
you could use YEAR() and MONTH() or as simple as:
WHERE
DateAction >= '2015-08-01 00:00:00'
and
DateAction < '2015-09-01 00:00:00'
This will not include the september date.
I think it may help you
Suppose if you want the result or records of August, you may user the query
SELECT * FROM Expenses WHERE DATE_FORMAT(DateAction,'%c')='8'

Fetch records from specific month and year in php and mysql

I have table where records are stored in 9/23/2014 this format of date.
I have searched a lot but all the result which i got there were in timestamp format(2013-12-27).
Can anybody help me, how retrieve data from specific month (say 'september' 2014)
Many thanks if help.
Table: events
id course description date start end
1 john test 9/23/2014 1:00pm 3:00pm
2 brad play 12/30/2014 5:00pm 8:00pm
My Code:
SELECT date FROM events WHERE MONTHNAME(date) = 'September' AND YEAR(date) = '2014'
You should use BETWEEN -
SELECT *
FROM `events`
WHERE `date` BETWEEN '2013-09-01' AND '2013-09-30';
Because your dates are stored as varchar's (you really should fix that) you'll have to convert the string to a date format and then search. The performance will be awful though -
WHERE STR_TO_DATE(`date`, '%m/%/d/%Y %h:%i:%s %p') BETWEEN STR_TO_DATE('2013-09-01', '%m/%/d/%Y') AND STR_TO_DATE('2013-09-30', '%m/%/d/%Y')
or
WHERE STR_TO_DATE(LEFT(`date`,LOCATE(' ',`date)),'%m/%d/%Y') BETWEEN '2013-09-01' AND '2013-09-30';
You can also use this method (although I prefer the first because of the control it offers) -
SELECT * FROM `table` WHERE YEAR(`date_column`) = 2013 AND MONTH(`date_column`) = 9;
EDIT: Updated to reflect the OP's table schema. You should always check reserved word information before naming your columns.
Simple try this:
$query = mysqli_query($connect,'SELECT columns FROM tablename WHERE MONTHNAME(datecolumnn) = 'September' AND YEAR(datecolumn) = '2014');
;)
You can try something like this:
SELECT * FROM my_table WHERE date_field BETWEEN DATE_FORMAT('%m/%d/%Y','2013-09-01') AND DATE_FORMAT('%m/%d/%Y','2013-09-30')
It should work.

mysql select query

I search and get 10 records as result.I have two drop down boxes.one will have month as value and other one will have year as the value.Say those 10 records have same year and 5 have month as jan and other five has month as feb.
When user clicks feb then five ids will be passed to my query but i need to pull the younger document.2 docs were inserted on 5th of feb and other tow 10 feb and remaining one 25feb.i need to pull this 25th feb document.
how to select this using select statement?
You can extract day and time from the database and have them shown to the user so he can select the correct document, otherwise you can solve with:
SELECT *
FROM TABLE
WHERE month = 'Feb'
AND year = 2011
AND day = (select max(day) from table where month = 'Feb' and year = 2011 )
But I'm supposing a lot of information here, these infos should help me help you out:
name of table
fields and field types
Do you have a way to keep correct track of timestamps and dates?
Presumably you have some date_inserted column in your database - if so, you can add
ORDER BY date_inserted DESC LIMIT 1
This will put them in reverse date order, and LIMIT 1 will cause it to only return 1 result
This should work:
SELECT *
FROM `table`
WHERE MONTH(`insert_date`) = 2
AND YEAR(`insert_date`) = 2011
ORDER BY `insert_date` DESC
LIMIT 1;
Note: the above assumes you have a field in your table for storing the date on which the document was created/inserted. Please replace insert_date and table in the above query with the respective column name and table name.
EDITED after this comment "date stores date,month stores month and year stores year"
SELECT *
FROM `table`
WHERE `month` = 2
AND `year` = 2011
ORDER BY `year` DESC, `month` DESC, `date` DESC
LIMIT 1;
I've assumed that in the month column you are storing numbers, 1 for Jan, 2 for Feb and so on. If however you are storing the 3-letter month name, then instead of "`month` = 2" please use this:
MONTH(STR_TO_DATE(`month`, '%b')) = 2
Hope this should work.

Categories