Comparing date from variable to MySQL date - php

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.

Related

How can I work with date in php and mysql?

I want to know how can I work with dates in MySQL and PHP. I want to know how many days remain, i want to know how many day is defference(distance) between nowTime and createTime ?
<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
////ISSET
if (isset($_POST['projectId'])) {
$projectId = $_POST['projectId'];
$result = mysql_query("SELECT *FROM projects WHERE projectId='$projectId'") ;
if (mysql_num_rows($result)>0) {
$result = mysql_fetch_array($result);
$response["title"]=$result["title"];
$response["exp"]=$result["exp"];
$response["userIdKarmand"]=$result["userIdKarmand"];
$response["userIdKarfarma"]=$result["userIdKarfarma"];
$response["cost"]=$result["cost"];
$response["zemanat"]=$result["zemanat"];
$response["time"]=$result["time"];
$response["createTime"]=$result["createTime"];
$response["type"]=$result["type"];
$response["nowTime"]=DATE("y-m-d");
$response["remainTime"]=DATE("y-m-d")- strtotime($response["createTime"])+$response["time"];
echo json_encode($response);
}
else {
}
}
else {
}
?>
It's not working. What can I do? I want compare createtime and nowtime and find out how many days I have time?
strtotime converts formatted string date format to timestamp. You can't substract timestamp data from string data. You have to first convert $response["remainTime"] to timestamp using strtotime() and then substract strtotime($response["createTime"]) from this value.
The best way to go through a MySQL result would be to loop through the fetch_assoc() function.
$result = mysql_query("SELECT * FROM projects WHERE projectId = '$projectId'");
// while() through an associative array from the MySQL object
while($result =& $result->fetch_assoc()) {
$response["title"] = $result["title"];
$response["exp"] = $result["exp"];
$response["userIdKarmand"] = $result["userIdKarmand"];
$response["userIdKarfarma"] = $result["userIdKarfarma"];
$response["cost"] = $result["cost"];
$response["zemanat"] = $result["zemanat"];
$response["time"] = $result["time"];
$response["createTime"] = $result["createTime"];
$response["type"] = $result["type"];
$response["nowTime"] = DATE("Y-m-d H:i:s"); // this is how you would need to format dates to work with MySQL
$remainTime = (strtotime($response['nowTime']) - strtotime($response['createTime'])); // this would return how many seconds have passed since $response['createTime'] until now
$response["remainTime"] = $remainTime;
}
echo json_encode($response);
This would allow you to have how many seconds since $response['createTime'] held in the $remainTime variable.

Update Automatic Mysql Values php

Hello I want to update MySQL table automatic at set time like i want to update table at 5:30 i have some values to update in my database at set time automatic. in PHP
$date = date('H:i:s');
if($date == "11:26:00") // 17:30:00 is equal to 5:30 but in 24 system
{
$sql1 = "SELECT * FROM No where id='1'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
while($row= mysqli_fetch_assoc($result1))
{
$Foo= $row['foo'];
}
$sql2 = "UPDATE No SET id='2',foo='$foo' where id='2'";
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
}
Just lie what Ashish said you can use CRON , and if you want you maybe can use this , i did not use before , try it . This code will works once ,so you have to find away to make loop cause the time will change every sec .
Note : Check the second code .
<?php
// Database connect
$date = date('H:i:s'); // Set the time to hours and minutes and seconds format
// you can echo $date to check how it looks but it will be something like this : 07:21:48
if($date == "17:30:00") // 17:30:00 is equal to 5:30 but in 24 system
{
// You can type your code here .
}
?>
Second Code :
<?php
// Remember to connect to your database
$date1 = date_create("00:00");
$date2 = date_create("23:59");
while($date1<=$date2)
{
date_add($date1,date_interval_create_from_date_string("1 sec"));
$a = date_format($date1,"H-i-s");
if($a =='17:30:00')
{
$sql1 = "SELECT * FROM No where id='1'";
$result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());
$row= mysqli_fetch_assoc($result1)
{
$Foo= $row['foo'];
$sql2 = "UPDATE No SET id='2',foo='$foo' where id='2'";
$result2 = mysqli_query($mysqli,$sql2) or die(mysqli_error());
}
die;
}
else
{
// you can type anything here , you can end the process by typing die; or anything you want
}
}
?>
You can check this and see how you can loop throw date in php :
I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?
This can help you understand the time and date system and how to change the format for the date in php : How to get the current date and time in PHP?

Trying to SELECT a record in an sqlite database using php

I am trying to select one record from the table tblTermDate. I am only getting an output of 1 for both. There is data entered into the fields and the format is VARCHAR for both dates. Any help would be appreciated Thanks!
<?php
// create or open database called TimeTable.sqlite
$db = #sqlite_open("TimeTable.sqlite");
//Get Start Date from Table
$StartDate = #sqlite_exec($db, "SELECT fldStartDate FROM tblTermDate WHERE fldTerm_Name ='Christmas 1st Half' ");
//Print Start Date
echo $StartDate;
echo "<br> </br>";
//Get Start Date from Table
$EndDate = #sqlite_exec($db, "SELECT fldEndDate FROM tblTermDate WHERE fldTerm_Name ='Christmas 1st Half' ");
//Print End Date
echo $EndDate;
//Database Close
#sqlite_close($db);
?>
sqlite_exec executes a SQL statement and does not return any rows. Its return value is true if the statement was executed successfully and false otherwise. Hence your "output" of 1.
What you are looking for is the sqlite_query method: http://www.php.net/manual/en/function.sqlite-query.php

php compare current date with dates stored in database

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';
}

Search with PHP for calendar dates within a MySQL array?

I'm building a calendar and I'm really dumb when it comes to arrays.
First of all, I need to query my database, so:
$events = mysql_query ("SELECT id,title,date WHERE date BETWEEN 2009-01-01 AND 2009-01-31")
or die(mysql_error());
So, now I need to order those events so, when I'm echoing my calendar table, I can check this array for events.
In this great Calendar written by David Walsh, he does a query for every day, but I suppose it would be a performance nightmare.
So...any ideas how can I do this?
First up, make sure you're comparing dates with dates. I think your code should be (i.e. with single quotes around date):
$events = mysql_query ("SELECT id,title,date WHERE date
BETWEEN '2009-01-01' AND '2009-01-31' order by date asc")or die(mysql_error());
assuming date is a date column.
i would do that in a elegant for loop
for($i=0;$i<30;$i++)
{
$events[] = mysql_fetch_array(mysql_query ("SELECT id,title,date WHERE date BETWEEN 2009-01-01 AND 2009-01-{$i}"));
}
now you have an array do somethingg with it like this
for($i=0;$i<count($events);$i++)
{
echo $events["id"];
}
will return each id for events in that array
Ok regarding your comments you can do something like this: Get the events like Davek proposed (note the ORDER BY!)
$events = mysql_fetch_assoc(mysql_query ("SELECT id,title,date WHERE date BETWEEN '2009-01-01' AND '2009-01-31' ORDER BY date asc"));
Then you got the events ordered by the date. To output it you can do this:
$last_date = null;
foreach($event in $events) {
if($last_date !== $event['date']) {
echo 'Events for day ' . $event['date'] . ": \n";
$last_date = $event['date'];
}
echo $event['title'] . "\n"
}
Note: This is just a rough sketch, you have to adjust the output of course, but it should give you the right idea.
Output would look like this (in my example):
Events for 2009-01-01:
Event 1
Event 2
Events for 2009-01-02:
Event 1
.
.
.
Edit after comment:
You can write your own function:
function get_events($date, $events) {
$result = array();
foreach($event in $events) {
if($event['date'] == $date) {
$result[] = $event;
}
}
return $result;
}
But this way you search the the complete array over and over again for each day. You can improve it, if you remove the events you already searched for from the $events array. So every time you search in a smaller array. But I would only do this if there is a performance issue.

Categories