php compare current date with dates stored in database - php

I am trying coding a php script where i want to extract a date field from a database table,store this date compare it with todays. To see if the data. from database has passed or not compared to todays date.
the code i have written for this functionality looks like its not working
I think i am getting the date() format wrong.
I am not to sure about the logic if statments.
php
$sql="SELECT enddate FROM campaigns WHERE id=".$data['camp'];
$result = mysqli_query($db, $sql);
while($info = mysqli_fetch_assoc($result)){
if(date("Y-m-d") > $result){
exit;
echo "Success";
}
elseif(date("Y-m-d") < $result){
return true;
echo "Failure";
}
}

Use strtotime()
while($info = mysqli_fetch_assoc($result)){
if(strtotime(date("Y-m-d")) > strtotime($result)){
exit;
echo "Success";
}
elseif(strtotime(date("Y-m-d")) < strtotime($result)){
return true;
echo "Failure";
}
}

You have to do:
if(date("Y-m-d") > $info['enddate']) {

Youl could just let MySQL worry about it.
SELECT DATEDIFF(NOW(),enddate) FROM campaigns WHERE id=".$data['camp']
That will return the number of days between the two dates. See the manual for DATEDIFF.

You can use below query :
$sql="SELECT (CASE WHEN DATE(NOW()) > enddate THEN 'success' ELSE 'failed' END) AS mystatus FROM campaigns WHERE id=".$data['camp'];
Then you just need to call mystatus column from the query.

I spend lot of time to compare only dates and i found a solution like this
Always set format like date('Y-m-d')
$dateTo='2016-08-07';
if(date("Y-m-d", strtotime($dateTo)) > date('Y-m-d')){
echo 'yes';
}else{
echo 'no';
}

Related

php mysql looking how to check if there are no result

I have this code
require("connession.php");
$contabilita="d";
$dataa="10/12/2018";
$datam_0=explode("/", $dataa);
$datam = "".$datam_0[2];
$result = mysqli_query($con,"SELECT Max(n_ricevuta)+1 as max_ricevuta
FROM corrispettivi_mod
where anno='$datam'
and contabilita='$contabilita'");
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) > 0){
echo $row['max_ricevuta'];
}
else{echo "1";}
here is my db
data anno n_ricevuta contabilita
2019-12-01 2019 1 nd
in my db I have only a row with a value of the filed 'anno' 2019 so it must print '1' but it doesn't.
if I modify in the db the field anno with the value "2018", it works.
help me thanks
When using an aggregate function like max() you will always get a row, if there isn't a matching row it will return null.
So you need to change your test to...
if($row['max_ricevuta'] != null){
echo $row['max_ricevuta'];
}
else {
echo "1";
}
As RiggsFolly also points out, worth checking the values your using in your testing, you have
$contabilita="d";
whereas the example data shows nd.

UPDATE Query not working - PHP/MySQL/bind_param

It's a simple update code in a PHP function through a GET call from the front-end(Not sure if this matters), the code is converting a particular time zone value to unix time stamps -
$oldDate = null;
$newDate = null;
$ctr = 0;
$timeStamp = array();
$query= $this->userDatabaseConnection->stmt_init();
$query->prepare("SELECT Timestamp from Transaction INNER JOIN `Order` ON `Order`.TransactionId = Transaction.TransactionId");
$query->execute();
$query->bind_result($tID); //this holds the current time zone values
while($query->fetch()){
$oldDate = $tID;
array_push($timeStamp, $oldDate);
}
$query->close();
foreach($timeStamp as $row){
$newDate = strtotime($row);
$queryUpdate= $this->userDatabaseConnection->stmt_init();
$queryUpdate->prepare("UPDATE `Order` SET OrderDate=? WHERE TransactionId=?");
error_log("ERROR!",0);
$queryUpdate->bind_param('is', $unixTS, $oldTS);
$unixTS = $newDate;
$oldTS = $row;
$queryUpdate->execute();
$queryUpdate->close();
$ctr++;
}
if($ctr == 88){
return true;
}
else{
return false;
}
}
The $ctr variable is returning the total number of rows that need to be updated - which equals to the correct value and thus returns a true to my front end Angular controller.
I tried echo-ing the $newDate and $row values - they seem to be correct too.
But it just does not update my table. Can someone please help me figure out why? Am I missing something here? The error log does show the message in my Apache log - but I can't seem to figure out what's causing it.

Date and Format issues in PHP

I am new here and this is my first question. Well, here it goes:
What I need to do is to create a PHP that compares an array of birthdays (dates) from a database (mysqli query) to the actual date (particularly month and day, ignoring the year for obvious reasons) so it can confirm "This person's birthday is today" through an echo or something.
I am having trouble formatting the date from the sql array. Here's what I got so far:
<?php
$link = mysqli_connect("localhost", "root", "", "employees");
$actualdate = date('md');
if (mysqli_connect_errno()) {
printf("Conection failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT BirthDate FROM Birthdays";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_row($result)) {
if (in_array($actualdate, $row)) {
echo "Birthday!";
} else {
echo "No birthday";
}
}
mysqli_free_result($result);
}
mysqli_close($enlace);
?>
Thanks beforehand, and sorry for the botherations.
Assume BirthDate is stored as a DATE. I would probably only select the Birthdays that are today:
SELECT BirthDate
FROM Birthdays
WHERE DAY(BirthDate) = DAY(NOW()) AND MONTH(BirthDate) = MONTH(NOW());
If you still want to echo "No birthday" you need to check the date format in the database. Normally the date format in the MySQL is YYYY-MM-DD. So you need to change the date creation code to
$actualdate = date('Y-m-d');
That will do.. Otherwise you can choose #jim's answer, to get only today's birthdays.

How do I adjust the Date Format when it is in an array?

I can't figure out how to isolate only the Date variable in an array that is pulling all of the keys from MYSQL. I want to make it format %M %d. How can I pull it out of $dataFields array modify it then put it back in? The Key is "Date".
include('include/connect.php');
$table='currentJobs';
$sql="SELECT * FROM `".$table."`";
$result=mysql_query($sql,$dbLink);
$data=array();
$d=0;
while($row=mysql_fetch_assoc($result)){
$dataFields=array();
while(list($key,$value)=each($row)){
$dataFields[]='<td class="'.$key.'" >'.$row[$key].'</td>';
if ($d==0){
$dataKeys[]='<th class="'.$key.'" >'.$key.'</th>';
}
}
if ($d==0){
$data[$d]='<tr>'.join('',$dataKeys).'<th class="actions">Actions</th></tr>';
$d++;
}
$data[$d]='<tr>'.join('',$dataFields).'<td>
Update</td></tr>';
$d++;
}
mysql_free_result($result);
if ($d>0){
echo '<table class="sortable">'.join('',$data).'</table>';
}
else {
echo 'Sorry, data was not found';
}
mysql_close($dbLink);
It is currently Displaying:
Date Name Phone Bike_Year Bike_Model Current_Status Service_Type ▴ Mechanic Revenue Notes Actions
0000-00-00 Test User 206-555-5555 2001 FLHRI Checked In Spec Service Interval Johhny 840.30 Update
$sql="SELECT
date_format(date, '%M %d') AS date,
Name,Phone,Bike_Year,Bike_Model,Current_Status Service_Type,Mechanic,Revenue,Notes
FROM `".$table."`";
This method is less efficient then just modifying the format within the SQL as suggested by JOE LEE. But either way works, whichever you prefer should work.
if($key == 'Date'){
$dataFields[]='<td class="'.$key.'" >'.date('M d',strtotime($row[$key])).'</td>';
} else {
$dataFields[]='<td class="'.$key.'" >'.$row[$key].'</td>';
}
or compact:
$dataFields[] = $key == 'Date' ? date('M d',strtotime($row[$key])) : $row[$key];
Look here for the date format options:
http://us1.php.net/manual/en/function.date.php

Comparing date from variable to MySQL date

I'm comparing date specified in PHP with dates in MySQL table and then echoing all rows with dates after the date in PHP. It works OK when I specify the date in the SELECT command, but when I make it a variable it doesn't work.
My PHP is:
$sql = "SELECT event FROM LifeEvents WHERE event_date > '1995-02-27'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["event"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
This works ok. But when I replace the SELECT with:
SELECT event FROM LifeEvents WHERE event_date > $date
It no longer works.
For the variable I've tried working with both:
$date = new DateTime('1995-02-27')
and
$date = '1995-02-27'
Neither of them works. The data type in MySQL is DATE.
For the string variable
$date = '1995-02-27'
$sql = "SELECT event FROM LifeEvents WHERE event_date > '$date'";
// this should work exactly as
$sql = "SELECT event FROM LifeEvents WHERE event_date > '1995-02-27'";
For the DateTime object, this should work
$date = new DateTime('1995-02-27')
$sql = "SELECT event FROM LifeEvents WHERE event_date > '" . $date->format(Y-m-d). "'";
I suggest you always set the timezone when you are dealing with dates and times because underestimate timezones can result in really bad bugs specially if your applications is dealing with many timezones and you have timestamp data type in your database.
make it a habit to do this
define('DEFAULT_TIMEZONE','UTC');//set this in your global config.php file
$date = new DateTime('2000-01-01', new DateTimeZone(DEFAULT_TIMEZONE));
Lets create a variable that holds a date and then convert it to date format that MySQL can understand.
$dt = date('Y-m-d', strtotime('1995-02-27')); // maybe filled dynamically
$sql = "SELECT event FROM LifeEvents WHERE event_date > '$dt'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["event"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
Then change what you want in order to serve your needs.
Hope I pushed you further.
That's because '1995-02-27' and DateTime('1995-02-27') are both not valid in that case :
'1995-02-27' would work if you'd have put extra quotes around $date in your SQL query : "SELECT event FROM LifeEvents WHERE event_date > '$date'"
DateTime('1995-02-27') doesn't have a __toString() magic method so PHP is unable to represent it as a string. You have to use the format method : $date = $date->format('Y-m-d') (and it will still miss the quotes)
One or another solution, you need to protect yourself against SQL injections using prepared statements! And you will actually no longer need any quote.
Try using the Carbon library for PHP.
Store a date with PHP:
$current_time = Carbon::now()->toDateTimeString();
Then just compare it the same way.

Categories