My database has y m d fields with no leading zeros in the month and day. I am trying to compare a records y-m-d against today's date. Greater than or equal show a greenlight image else red light. It's not working! HELP!
$q = "SELECT * FROM pec_mbbtmssgs WHERE activity='bike' AND CONCAT(`y`,'-','m','-','d') >= date('Y-n-j')";
$r = mysql_query($q);
$row = mysql_fetch_assoc($r);
$activity = $row['activity'];
if($activity == "bike") {
$image = "greenlight25";
}
else {
$image = "redlight25";
}
echo '<img src=http://img/' . $image . '.gif />';
?>
Your usage of CONCAT() is a bit off, as database-columns should either be wrapped in backticks or nothing at all, and strings/separators in singlequotes '.
You can also just do DATE(NOW()) to get the current date, and compare against this. Then you use the DATE() with the result of your CONCAT(), so it becomes like this
SELECT *
FROM pec_mbbtmssgs
WHERE activity='bike'
AND DATE(CONCAT(y, '-', m, '-', d)) >= DATE(NOW())
The simpler approach would be to just store your date in a DATE type column, instead of 3 separate ones. You can always extract the specific information you want (e.g. you can extract the month, even if your value is 2016-11-30).
$q = "SELECT * FROM pec_mbbtmssgs WHERE activity='bike' AND unix_timestamp(CONCAT(`y`,'-',`m`,'-',`d`)) >= unix_timestamp(CURDATE())";
Related
I am getting Values out of a MySQL Table and my Date looks like: DD.MM
Now I want to check if this Date is in the past. I tried it with if($ende < date("d.m")); but it deleted values like 01.11 at the 23.10.
I need to remove entries that are in the past.
My Code Looks like:
if($ende < date("d.m")) {
$sqls = "DELETE FROM hausaufgaben WHERE Ende='$ende';";
if(!mysqli_query($conn, $sqls)){
echo "<p>Es gab keine älteren Hausaufgaben</p>";
}
}
Split the date so that it is in two parts, then compare the day and month seperately
$ende = "01.11";
$ende_split = explode( '.', $ende );
$ende_tag = $ende_split[0];
$ende_monat = $ende_split[1];
if( ($ende_tag < date('d')) && ($ende_monat <= date('m')) ){
$sqls = "DELETE FROM hausaufgaben WHERE Ende='$ende';";
if(!mysqli_query($conn, $sqls)){
echo "<p>Es gab keine älteren Hausaufgaben</p>";
}
}
monat uses <= because the month can be the same, but the day can be in the past.
You will need to use Str_To_Date() function, to convert your DD.MM format string to MySQL Date format (YYYY-MM-DD).
Since you mentioned that there will be data only from the current year; I can safely assume that the year is 2018 (It can be made generic by using YEAR(CURDATE()).
Try the following query instead:
DELETE FROM hausaufgaben
WHERE STR_TO_DATE(CONCAT(Ende, '.', YEAR(CURDATE())),
'%d.%m.%Y') < CURDATE()
Additional Details:
%d Day of the month as a numeric value (01 to 31)
%m Month name as a numeric value (00 to 12)
%Y Year as a numeric, 4-digit value
Im using the following mysql script to display a list of active / upcoming fixtures.
Select * FROM schedule
WHERE schedule.gameDate > CURDATE() OR
( schedule.gameDate = CURDATE() and schedule.gameTime > CURTIME() )
GROUP BY schedule.tournament
ORDER By schedule.gameDate
The above script works perfectly.
However, as an additional check to prevent a user from accessing a fixture which has expired im doing the following.
$curTime = date('H:i:s');
$curDate = date('Y-m-d');
$sql = "SELECT * FROM schedule
WHERE tournament = :tour AND weekNum = :round";
$stmnt = $db->prepare($sql);
$stmnt->bindValue(':tour',$tournament);
$stmnt->bindValue(':round', $round);
$stmnt->execute();
$results = $stmnt->fetchAll();
foreach($results as $result){
echo $eventDate = $result['gameDate'];
echo $startTime = $result['gameTime'];
if($curDate > $eventDate){
echo '<h1> CURRENT ROUND ALLREADY STARTED</h1>';
die();
}//if
else if($eventDate==$curDate && $curTime>$startTime){
echo '<h1> CURRENT ROUND ALLREADY STARTED</h1>';
die();
}//else if
}//foreach
My Problem.
The loop never passes the first IF statment which always results to true...
DB Table
When I echo the variables I get the following:
$curTime = 09:30:00
$curDate = 2017-19-03
$eventDate = 2017-03-21
$startTime = 13:00:00
I realize it is not the prettiest code but according to my little experience and logic it should pass both if statments...
Any advise appreciated
Use strtotime() in compare two date in php
Replace if($curDate > $eventDate) with if(strtotime($curDate) > strtotime($eventDate)) and other comparison also
You can convert them to DateTime objects or timestamps to compare. String comparison will only check whether they are equal or not.
So:
$now = new DateTime();
$event = new DateTime($eventDate . ' ' . $startTime);
Then you can check whether dates are equal or later the same way you're already doing. See Example #2 on the Date Diff page of the php website. E.g. $now > $event, etc.
It should be elseif.not else if. There should not be a space between else and if.
I want to select names which expires in this month and two months ahead.
$t=date('Y');
$q = date('m');
for($e=$q;$e<=($q+2);$e++){
$ren = $t.'-'.$e;
$sql = "select name,renewal_date from hosting_details where renewal_date LIKE '$ren%' ";
}
In this first month display correctly but then onward doesn't give any result. when i echo $ren,for the first month it gives 2016-01 and second month 2016-2.
how can i resolve this
You could simply use sprintf() to format the numbers. For example:
$t=date('Y');
$q = date('m');
for($e=$q;$e<=($q+2);$e++){
$ren = $t.'-'. sprintf("%'.02d", $e);
var_dump($ren);
}
More info on sprintf() can be found in the docs.
However since you're working with dates, why not use a \DateTime object and have it do the work for you? This means you don't have to do any date overflow logic etc - PHP does all the complex work for you! :) e.g.
$begin = new DateTime( '2016-01-11' );
$numMonths = 2;
for($i=0; $i<$numMonths; $i++)
{
// e.g. increment the month and format the date.
var_dump($begin->modify( '+1 month' )->format("Y-m-d"));
// of course modify the format to "Y-m" for your code:
// $ren = $begin->modify( '+1 month')->format("Y-m");
}
For more reading you can checkout \DateTime and \DatePeriod in the PHP docs.
Here's a working example comparing the two approaches.
Using sprintf() can solve your problem:
$t=date('Y');
$q = date('m');
for($e=$q;$e<=($q+2);$e++){
$ren = sprintf('%d-%02d', $t,$e);
$sql = "select name,renewal_date from hosting_details where renewal_date LIKE '$ren%' ";
echo $sql . "\n";
}
Output:
select name,renewal_date from hosting_details where renewal_date LIKE '2016-01%'
select name,renewal_date from hosting_details where renewal_date LIKE '2016-02%'
select name,renewal_date from hosting_details where renewal_date LIKE '2016-03%'
I am trying to compare two date strings of type d/m/y, but it seems that something with the comparison of that type of dates doesn't work. I thought to use DateTime PHP's function, but at first I want to learn why the script above doesn't work.
Here is the code:
public function listActiveNews(){
$today = strtotime(date('d/m/Y'));
$db = mysql_init();
$sql = "SELECT * FROM ph_news WHERE newActive = 1";
$prq = $db->prepare($sql);
$prq->execute();
foreach($prq->fetchAll(PDO::FETCH_ASSOC) as $fetch){
$dateFrom = strtotime($fetch['newsDateFrom']);
$dateUntil = strtotime($fetch['newsDateUntil']);
if ( ($today >= $dateFrom) && ($today <= $dateUntil) ){
print date('d/m/Y') . " >= " . $fetch['newsDateFrom'] .
" && " . date('d/m/Y') . " <= " .
$fetch['newsDateUntil'] ."<br>" ;
print $fetch['Title'];
}
}
}
I am getting this result and I cannot understand why the comparison of these dates returns TRUE in the if clause.
Output:
28/02/2014 >= 20/03/2014 && 28/02/2014 <= 27/02/2014
Title
Here are the dates values:
date('d/m/Y') = 28/02/2014
$newsDateFrom = 20/03/2014
$dateUntil = 27/02/2014
Really... stop abusing the date system. $today = strtotime(date('d/m/Y')); is utterly pointless. $today = time() is the less convoluted and far more efficient version.
Plus, why are you doing the time filtering in PHP when you could simply do it in MySQL?
SELECT *
FROM ph_news
WHERE (newActive = 1) AND (curdate() BETWEEN newsDateFrom AND newsDateUntil)
will fetch only the records you actually want. Right now you're fetching pretty much the entire table, and then throwing away most everything except the few records you really did want.
I use PHP to perform SQL to pull out some data from my database between a date range. The dates are stored as date in the relation:
$from = "2011-08-11";
$to = "2011 - 08- 25";
$query = mysql_query("SELECT date FROM `entries` WHERE date BETWEEN '$from' AND '$to' ORDER BY date ASC");
I would like to find the earliest date pulled from the relation.
If the query is successful, I store the 'date' attribute in a php array called $dates. I thought I could iterate over this $dates and compare the $date values after converting them into dates.
if($query){
$dates = array();
while($row = mysql_fetch_array($query)){
$dates[] = $row['date'];
}
$min = strftime("%Y-%m-%d", strtotime($dates[0]));
for($i = 1; $i < count($dates); $i++){
if($dates[i] < $min){
$min = $dates[i];
}
}
This does not work however...It prints random values....Perhaps there is a much simpler way to do this and I am overcomplicating matters...
HEEEELLLP!!
If you order your query, then it will be the first (or the last) row in you're query. So you wouldn't need to find it.
Instead of
$min = strftime("%Y-%m-%d", strtotime($dates[0]));
you should use
$min = date("%Y-%m-%d", strtotime($dates[0]));
The simplest way is to use the first date since you know it is already the earliest due to ASC in your SQL statement. After you read the rows into your array, just use the first element.
while($row = mysql_fetch_array($query)){
$dates[] = $row['date'];
}
$earliest_date = $dates[0];
If all you want to do is find just the earliest date, and you don't care about the rest, you could use the aggregate function min() in your query like so:
SELECT MIN(date) AS earliest FROM `entries` WHERE date BETWEEN '$from' AND '$to'
Then just grab the earliest column from the result set in your php code.
Convert the dates to numbers and sort the array?
Take what you have (lines 1-5),
foreach ($dates as $date) {
// convert each date from "YYYY-MM-DD" to "YYYYMMMDD" and turn it into an int
$date = intval(str_replace("-", "", $date));
}
// sort the array from lowest to highest
asort($dates);
// the minimum is the first item in the array
$minint = $date[0];
// convert back into "YYYY-MM-DD" format
$min = substr($minint, 0, 4) . "-" . substr($minint, 4, 6) . "-" . substr($minint, 6);