I have users in a MySQL database, where their birthdays are stored in a DATE format (yyyy-mm-dd). I want to select users in the database with PHP who are between a certain age range.
What I have is a minimum age(18) and a maximum age(21). I know I can do something with BETWEEN, but the problem is that I only know the years and not the dates.
Does anyone have a suggestion on how I can do this?
This is what I'm doing currently:
function leeftijden($age) {
$morgen['day'] = date('d');
$morgen['month'] = date('m');
$morgen['year'] = date('Y') - $age;
$datum = $morgen['year'] .'-' .$morgen['month'].'-' .$morgen['day'];
return $datum;
}
Then I do this:
$maxDatum = leeftijden(18);
$minDatum = leeftijden(32);
$sqlRijder = "SELECT * FROM rijder WHERE geboortedatum between '".$minDatum."' AND '".$maxDatum."'";
But this doesn't work 100%.
How can I only select users who are between 18 and 21 years of age?
You can simply do it right in the query:
SELECT *
FROM rijder
WHERE geboortedatum BETWEEN
CURDATE() - INTERVAL 21 YEAR AND
CURDATE() - INTERVAL 18 YEAR
This way, you do not need a special PHP function to construct a DATE string. Simply pass in the numbers and MySQL will make the comparisons for you. Just make sure the higher number comes first in the BETWEEN.
Try this :::
Select * from table where (DATEDIFF(dob, DATE(NOW())) / 365.25) between 18 and 21
SELECT * FROM rijder
WHERE geboortedatum
between date_add(curdate(), interval -18 year)
and date_add(curdate(), interval -21 year)
try this
SELECT * FROM rijder WHERE DATEDIFF(NOW(), geboortedatum)/365.25 BETWEEN 18 AND 21
Related
I have a mysql table orders in that I have a column order_date which is current time stamp(2016-08-17 00:00:00.000000). now I want to select or count the data's entered this month and the previous month, after this I can find the difference between these two months I am using this code and it is not working.
$sql="SELECT * FROM order WHERE order_date > DATE_SUB(NOW(), INTERVAL 1 MONTH)";
$result = $this->db->query($sql);
return $result;
this is not working an mysql error is produced.
Try
$sql="SELECT * FROM order WHERE DATE(order_date) LIKE DATE_SUB(CURDATE(), INTERVAL 1 MONTH)";
$result = $this->db->query($sql);
return $result;
i think this Link[http://sqlhints.com/2015/07/10/how-to-get-difference-between-two-dates-in-years-months-and-days-in-sql-server/] will help you
Use this. Hope it helps what you want. Thanks
$todayDate = date('Y-m-d');
$todayMonth = date("m", strtotime($todayDate ));
$previousMonth = $todayMonth - 1;
$sql = "SELECT * FROM order WHERE MONTH(order_date) BETWEEN '$todayMonth' AND '$previousMonth'";
First, the following is the correct logic to get all values from the current month and all of the previous month:
select *
from orders o
where order_date >= date_sub(date_sub(curdate(), interval day(curdate) - 1 day), interval 1 month);
Then, use conditional aggregation for comparison. Here is an easy way:
select sum(month(order_date) = month(curdate())) as cur_month,
sum(month(order_date) <> month(curdate())) as prev_month,
(sum(month(order_date) = month(curdate())) -
sum(month(order_date) <> month(curdate()))
) as diff
from orders o
where order_date >= date_sub(date_sub(curdate(), interval day(curdate) - 1 day), interval 1 month);
Note: I don't fully see the utility of comparing a partial month (this month) to a full month (last month), but that is what you seem to be asking for. If you are asking for something different, then ask another question with sample data and desired results.
I am trying to grab the newest records from my table. I want all of the records that happened in the past 7 days. Here is what I have so far to start with.
$query = "SELECT * FROM mlg_logattempts AS a WHERE a.ts = (SELECT MAX(ts) FROM mlg_logattempts AS b WHERE b.ts > NOW() - INTERVAL 5 MINUTE AND b.name = a.name)";
I have used intervals in the past but an unsure how to make this work now. Can someone show me the proper way to request the past 7 days records? I do have a timestamp field.
UPDATE
Unfortunately I realized the command I shared with you. I do not have any of the above fields. The only date field I have is "date". no a or ts.
You could use mysql date_diff() for dates
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff
but since you use timestamps, the interval is a good solution:
b.ts > unix_timestamp(CURDATE()-INTERVAL 7 DAY)
Supposing that the date of login attempt is b.ts and it's formatted like 2013-08-20 03:08:
$past7days = date("Y-m-d H:i:s",strtotime("-7day"));
$query = "SELECT * FROM mlg_logattempts AS a WHERE a.ts = (SELECT MAX(ts) FROM mlg_logattempts AS b WHERE date >= '$past7days' AND b.name = a.name)";
I have a table with the following fields:
id - int
name - int
the_date - int
the_date is a unix timestamp for when the row was added
Now I am trying to write a query that will select all rows on the day that is 7 days from now. I'm not talking about select the rows >= 7 days from time(), I need to grab the current day using time(), and then run a SELECT that grabs all the rows that were inserted on the day that is 7 days from the time().
I know how to do it so its within 7 days from the time() with a simple >= SELECT, but I don't know how to do it so it selects all rows whose unix timestamp is on that particular day (7 days from now).
Any help would be greatly appreciated.
The points of intrest here,
i use curdate() to get the current DATE, not DATETIME.
i add 7 days and convert to unix time, which yields the starting second of that day
i do the same for the next day
i structure the where clause to be >= or equal to the target day, but < the start of the next day. This gives a range of seconds that fully covers the target day.
i dont use any functions on the column itself. This is important because if i did, mysql wouldn't be abl;e to use any indexes that exist on the column to fullfill the query.
where the_date >= unix_timestamp(curdate() + interval 7 day)
and the_date < unix_timestamp(curdate() + interval 8 day)
SELECT * FROM `dbname1`.`test`
WHERE
date(FROM_UNIXTIME(`the_date`)) = ADDDATE(DATE(NOW()), INTERVAL 7 DAY);
$todayParts = getdate();
$startToday = mktime(0, 0, 0, $todayParts['mon'], $todayParts['mday'], $todayParts['year']);
$sevebDaysFromNow = 60 * 60 * 24 * 7;
$seventhStart = $startToday + $sevebDaysFromNow;
$seventhEnd = $seventhStart + 60 * 60 * 24;
$sql = "SELECT * FROM <table> WHERE the_date BETWEEN $seventhStart AND $seventEnd";
This will calculate 7 days from the start of the day you are now. Hope this helps
how would I generate a MySQL query to grab a row that is between a particular month
eg grab row where month is between 01/01 (1st Jan) and 01/06 (1st June)
I'm not sure, if you want to grab all rows from Jan to June, only the rows until June 1st or all rows from Jan to May. You can use for example:
[...] WHERE `date_column` BETWEEN '2012-01-01' AND '2012-06-01'
which gives you all rows including June 1st.
Use this to get all rows from the full months of Jan to June:
[...] WHERE YEAR(`date_column`)=2012 AND MONTH(`date_column`) BETWEEN 1 AND 6
(change to BETWEEN 1 AND 5 for Jan to May)
If you generate your SQL query in PHP, you can use BETWEEN
$date = date("Y") . '-' . date("m") . '-01';
$sql = "SELECT *
FROM `table`
WHERE `date_column` BETWEEN '$date' AND '$date' + INTERVAL 1 MONTH - INTERVAL 1 DAY";
(I subtracted one day to exclude the data of the next month first day)
Or you can use EXTRACT
$month = 5;
$sql = 'SELECT *
FROM `table`
WHERE EXTRACT(MONTH FROM `date_column`) = ' . $month;
Assuming the column in mysql is the right format (date/datetime) you can simply compare (>,<) :
SELECT somecolumn
FROM sometable
WHERE datecolumn >= '2012-01-01' AND datecolumn < '2012-06-01'
Hope it helps!
You can use the month(), year() and day() functions. So your query would look like something like
SELECT * FROM table WHERE month(date_field) >= 1 AND month(date_field) <= 6 AND year(date_field) = 2011
date_field should be a date or datetime field, if it is a timestamp, you need to use the FROM_UNIXTIMESTAMP function so it would look like month(FROM_UNIXTIMESTAMP(timestamp_field))
SELECT
*
FROM
yourtable
WHERE
date BETWEEN '2012-01-01' AND '2012-06-01';
I have a user table, where users need to be approved, i want to show users who are not approved and is registered more than 7 days ago.
My user_regdate is a timestamp created with php time() function.
This is what i try, it does not works:
mysql_query("select * from users WHERE user_regdate < now() - interval 7 day AND approved='0' order by id;");
Thanks
PHP's timstamps are a simple integer, whereas MySQL's now() returns a datetime value. Most likely this will fix up the query:
SELECT ... WHERE user_regdate < unix_timestamp(now() - interval 7 day)) ...
Basically, without the unix_timstamp() call, you're comparing apples and oranges.
Primitive solution at best, but im not the best at MySQL time calculation
$timestamp = strtotime("-7 days");
mysql_query("SELECT * FROM users WHERE user_regdate < $timestamp AND approved = 0 ORDER BY id");
php's time() function outputs a unix timestamp (the number of seconds since January 1 1970). MySQL's now() function outputs a formatted date (like 2011-6-9 12:45:34)... so I don't think you can compare them like that.
Try using the unix timestamp, minus 7 days, instead of now() in your query:
$7_days_ago = time() - (7 * 24 * 60 * 60);
mysql_query("select * from users WHERE user_regdate <" . $7_days_ago . " AND approved='0' order by id;");
Try this;
select *
from users
WHERE DATE_SUB(user_regdate,INTERVAL 7 DAY)
AND approved='0'
order by id;