php mysql getting count WHERE BETWEEN AND - php

Hey i have a little problem when i'm trying to get count of rows from table, where date is BETWEEN 2012-09-01 AND 2012-09-32...
Could you please tell me where's the problem?
$month = date(m);
$year = date(Y);
$day_start = '01';
$day_end = '32';
$from = $year.'-'.$month.'-'.$day_start;
$till = $year.'-'.$month.'-'.$day_end;
$result1 = $mysqli->query("SELECT COUNT(id) FROM `dreams` WHERE dream_state='dream' AND date BETWEEN $from AND $till");
$row1 = $result1->fetch_row();
$this_dream = $row1[0];
i've tryed to convert the string to time and from time to date like this:
$from = strtotime($from);
$from = date("Y-m-d",$from);
$till = strtotime($till);
$till = date("Y-m-d",$till);
but still doesn't work, so any ideas?
Thank you.

First of all, your date column needs to be some kind of date datatype, like DATE or TIMESTAMP.
Second, you need to use valid dates for comparison. September 32 is no good. When MySQL tries to interpret that date it gets NULL. All comparisons between real values and NULLs come up false. So, you get an empty result set.
Third, BETWEEN is terrible for date comparison ; it often fouls up the end -- the last day -- of the range.
I suggest you use a query like this. Notice that the second date comparison to is the day after the end of the range you want.
$month = date(m);
$year = date(Y);
$day_start = '01';
$from = $year.'-'.$month.'-'.$day_start;
$result1 = $mysqli->query("SELECT COUNT(id)
FROM `dreams`
WHERE dream_state='dream'
AND date >= '$from'
AND date < '$from' + INTERVAL 1 MONTH");
$row1 = $result1->fetch_row();
$this_dream = $row1[0];

You include dashes in your dates but don't quote them as strings in the SQL. There are no date literals in SQL, so you have to represent dates as strings upon entry. Simply enclose them in single quotes to represent SQL value strings.
$result1 = $mysqli->query("SELECT COUNT(id) FROM `dreams` WHERE dream_state='dream'
AND date BETWEEN '$from' AND '$till'");
You also have an invalid date, as no month has 32 days. Computing the last day of each month seems a bit of an overkill here, so you're probably better off describing the first day of the next month, and using < to exclude it from the range.
A previous version of this answer suggested using numbers to describe dates instead of strings. While this works, it might be quite bad for performance, as #ypercube pointed out in a comment below.

Related

trying to hide an event two days after it's passed

I'm trying to hide an event two days after it's passed in php (using a mysql query). There are two date options. Start date, and End date. I can't seem to figure out how to make the query work.
$query->select('*');
$query->from('#__events_items');
$query->where('date2 >= "'.$today.'"');
$query->where('date2 <= "'.$sixmths.'"');
$query->where('state = 1');
$query->order('date1 asc');
I've tried
$today = #date('Y-m-d');
$enddate = #date('Y-m-d',(strtotime(#date('Y-m-d')."+ 2 days")));
But obviously the end date won't be greater or equal to $enddate.. Any help would be greatly appreciated!
You can either modify today like so:
$today = date('Y-m-d', strtotime('-2 days'));
Or modify your query like so :
$query->select('*');
$query->from('#__events_items');
$query->where('date2 >= "'.$today.'" - INTERVAL 2 DAY');
$query->where('date2 <= "'.$sixmths.'"');
$query->where('state = 1');
$query->order('date1 asc');
I would say the second is probably better form since having $today represent two days ago would be nasty self documenting code.

Calculate age from birthdate in PHP

A friend of mine gave me this code, but I can't seem to get it to work. It keeps telling me that I have an undefined variable, but I have tried to define it several different ways, but it doesn't show their right age, it shows everyone as 43. Here is the code I'm using:
$bdate= getdate('$_GET["bd"]');
if($bdate == 0){ $nodate = 1; }
$bdate = strtotime( $bdate );
$birthday = date("n/j/Y",$bdate); //must be as m/d/yyyy
$bday = explode("/", $birthday); //parse
$b_mm = $bday[0]; //birthday month
$b_dd = $bday[1]; //birthday day
$b_yyyy = $bday[2]; //birthday year
//compare timestamps of mm/dd for birthday and today
$bday_mm_dd = mktime(0,0,0,$b_mm,$b_dd,0);
$today_mm_dd = mktime(0,0,0,date("m"),date("d"),0);
$age = date("Y", time()) - $b_yyyy;
if ($bday_mm_dd > $today_mm_dd) {
//birthday hasnt happened yet this year
$age = $age - 1;
}
Just for clarification in my sql statement I have the birthdate listed as bd.
If anyone can help, I would greatly appreciate it.
getdate() returns an associative array, not a textual representation of a date. strtotime() can't make sense of this, and your first call to date() then interprets its timestamp argument as zero, the UNIX epoch.
Guess how many years ago the epoch was? :)
Skip strtotime() and just pass $bdate[0] to date(). That will contain the epoch timestamp representation of 'bd'.

Search between dates (date as VARCHAR)

I have several dates stored as varchar in the following format: 01-01-2012
I want to search between dates, but sadly it isn't working as I expected. I looked for other threads which have the same question (kinda), but the answers provided there didn't work for me.
Here is my code:
$fromday = $_POST['fromday'];
$frommonth = $_POST['frommonth'];
$fromyear = $_POST['fromyear'];
$tillday = $_POST['tillday'];
$tillmonth = $_POST['tillmonth'];
$tillyear = $_POST['tillyear'];
$vanaf = "$fromday-$frommonth-$fromyear";
$tot = "$tillday-$tillmonth-$tillyear";
// zoeken
$sel = "SELECT * FROM bestelling WHERE verzenddatum >= '$vanaf' AND verzenddatum <= '$tot'";
$dosel = mysql_query($sel) or die(mysql_error());
while($row = mysql_fetch_assoc($dosel))
{
$datum = $row['verzenddatum'];
echo $datum;
}
Please let me know what I'm doing wrong!
It is not returning any rows because the query is not doing the comparison on valid DATE or DATETIME fields. You should be storing the dates as a DATE type, but what you could do is this:
// Switch the order of date elements:
$vanaf = mysql_real_escape_string("$fromyear-$frommonth-$fromday");
$tot = mysql_real_escape_string("$tillyear-$tillmonth-$tillday");
$sel = "SELECT * FROM bestelling WHERE STR_TO_DATE(verzenddatum, '%d-%m-%Y') BETWEEN '$vanaf' AND 'tot'";
The mysql_real_escape_string() function simply reduces the risk of SQL injection, which is what your original code was vulnerable to.
The MySQL function STR_TO_DATE() converts a string to a valid MySQLDATE type. %d-%m-%Y is the format you have in your varchar string currently, but STR_TO_DATE converts it to '%Y-%m-%d' which MySQL can then use to make range comparisons.
Also, I'm using the BETWEEN syntax in the SQL as it is the same thing as val >= val1 AND val <= val2. It's just clearer and simpler: val BETWEEN val1 AND val2.
You need to store the dates as either DATE field types or DATETIME field types. Migrate your database with a script (shouldn't be too hard on a small DB: Backup your table, convert all of your dates to the proper format, change the schema and then re-insert your data. Restore your backup if it explodes.) After fixing this, everything will work as expected.
I would strongly recommend that you fix this by converting the fields to proper DATE fields now and take the pain, rather than waiting until the inevitable performance problems that this approach will incur arise. If you cannot, try this:
$fromday = $_POST['fromday'];
$frommonth = $_POST['frommonth'];
$fromyear = $_POST['fromyear'];
$tillday = $_POST['tillday'];
$tillmonth = $_POST['tillmonth'];
$tillyear = $_POST['tillyear'];
$sel = "SELECT * FROM bestelling WHERE SUBSTRING(verzenddatum, 7, 4) BETWEEN '$fromyear' AND '$tillyear' AND SUBSTRING(verzenddatum, 4, 2) BETWEEN '$frommonth' AND '$tillmonth' AND SUBSTRING(verzenddatum, 1, 2) BETWEEN '$fromday' AND '$tillday';"
(The hope here is that if a record's date lies outside the "from year" and "to year", the MySQL query optimiser will notice this and bail out early)
MySQL's standard date format is 'year-month-day' try this $vanaf = "$fromyear-$frommonth-$fromday"; and do the same for $tot. Try that and see if it works.
Some theory:
$startdate = sprinf('%04d-%02d-%02d', $year, $month, $day);
$enddate = sprinf('%04d-%02d-%02d', $year, $month, $day);
$query = "SELECT * FROM orders WHERE date BETWEEN '{$startdate}' AND '{$enddate}'";
My tipp: Invest some time in PDO and prepared statements. Dont use mysql_ functions anymore.
Since you are using PHP, you can set your data type in MySQL to INT (Integer) and use UNIX Timestamps for your dates. This is a good way to search for greater than and less than values.
You can use something like:
$fromday = strtotime($_POST['fromday']);
Change Only Mysql query it's Working.
select * from Your_table_name
where STR_TO_DATE( "your_date_field" , '%d/%m/%Y' )
BETWEEN STR_TO_DATE("your_first_date", '%d/%m/%Y')
AND STR_TO_DATE("your_second_date", '%d/%m/%Y')

Figuring out the difference in days between events

I have a MySQL DB with StartDates in the format of yyyy-mm-dd and starttimes in the format of HH:MM using a 24 hour clock. What would be the easiest way to compare the difference of two days in PHP? Would using a datetime object could I set it to be with the information given and just give it to zeros for the seconds? I need to get the amount of time between both dates down to the minute. I was putting the startdate (Just the day since its always within the same month for my application) and time together concatenated together and then pulling out what I need like below, but I haven't been able to get it straight yet. Thanks for the look!
$tempvar1 = $times[$i][$j];
$tempvar2 = $times[$i][$j+1];
$day1 = $tempvar1[0].$tempvar1[1];
$day2 = $tempvar2[0].$tempvar2[1];
$hours1 = $tempvar1[2].$tempvar1[3];
$hours2 = $tempvar2[2].$tempvar2[3];
$minutes1 = $tempvar1[5].$tempvar1[6];
$minutes2 = $tempvar2[5].$tempvar2[6];
$numdays = ($day2-$day1) - 1;
$time1 = ($hours1*60)+$minutes1;
$time2 = ($hours2*60)+$minutes2;
MySQL has plenty of date/time functions:
SELECT TIMEDIFF(endtime, starttime), DATEDIFF(endtime, starttime)
FROM ...
doc links for timediff and datediff
That'll you get strings in the format of 'hh:mm:ss.ssss' for timediff, and a straight-up integer representing the days between the two dates, respectively.

Date comparison with PHP and Mysql

I have a table with a date field type date.
What I am trying to do is to do a comparison between the date from inside the table and the today date. If the date from the table is yesterday then insert the today date.
The thing I'm not sure about is how to insert the data in the database so I can make the comparison. here is what im thinking to do"
$d = time();
$x = mysql_querry("SELECT date FROM table where id = $id", $con);
while($y = myqsl_fetch_array($x)){
$oldTime = $y['date'];
}
if ($oldTime < $d){
$i = mysql_querry("INSERT INTO table (date) VALUES (CURDATE()) ", $con);
}
So, I'm not sure if $oldTime and $d can be compared like that, but I hope you guys get my point.
Any ideas?
Thanks
You can't do in that way because the CURDATE() function return a date in a format like 2011-11-11 while time() returns the number of seconds since the January 1 1970 00:00:00 GMT.
Anyway you can change the format of the time() to look like the CURDATE() using the date() function in this way:
date('Y-m-d', time())
or even better, to get the current date, you can use just this line:
date('Y-m-d')
To conclude, you can do the if in this way:
if( strtotime($oldTime) < strtotime(date('Y-m-d')) )
or even better:
if( strtotime($oldTime) < strtotime('now') )
To compare dates you can use strtotime($date); Where date can be a time(), mysql date or date('Y-m-d'); string

Categories