How to compare two datetime in mysql query using php - php

I want to compare two datetime variable witch one of them is current server time and one of them is stored in mysql database i am running this simple piece of code and it wont work and says it is a syntax error i am wondering what can i do
<?php include("includes/student_session.php");?>
<?php confirm_logged_in();?>
<?php include("includes/connection.php");?>
<?php
date_default_timezone_set("");
$now_date=date("Y-m-d H:i:s");
$query1="select exam_id from exam where {$now_date} > start_date";
$result=mysqli_query($cnn,$query1);
if($result){
$row=mysqli_fetch_array($result);
echo $exam_id. "exists";
}else
{echo mysqli_error($cnn);}
?>

In this code:
$query1="select exam_id from exam where {$now_date} > start_date";
$result=mysqli_query($cnn,#query1); // <-
You are using #query1, this should be $query1.

$query1="select exam_id from exam where {$now_date} > start_date";
$result=mysqli_query($cnn,#query1);
I think the error is because you are using # insteal of $.
Also your query seems to be wrong. You should compare values with fields change it to
$query1="select exam_id from exam where start_date > '{$now_date}'";
$result=mysqli_query($cnn,$query1);

Even if correct the misstype of #query1 the query will not work like this. $now_date is a string and you have to pass it to the query like a string. Even better if you format it with mysql's functions, not with php's one as well as compare time stored in database with database's own time (then you can skip any timezone problems). So, your query, for example, could be like this:
SELECT exam_id FROM exam WHERE DATEDIFF(NOW(), DATE_FORMAT(start_date,'%Y-%m-%d %T')) > 0;

Related

Difference between now() and one column with datum (date) in MySql

I don't have too much experience with the PHP programming language, so I ask you for help solving a small problem.
I have several users in the tabele with their data and one column that lists the date when they need to report to the interview.
I need a sql query syntax to check the following:
Does the database have a user whose date in the table is the same or larger than it currently is. If a user is found, then my program will send an email to remind him.
I will use CRON JOB after to refresh the index.php, thats okay, but bothers me the most that I don't know the date comparison syntax.
Otherwise the date in mysql database for each user is entered in the format 2020-02-15
$datenow = date("Y-m-d");
echo $datenow;
$sql = "SELECT * FROM 'users' WHERE 'report_date' >= '".$datenow."'";
if ($result = mysqli_query ($con, $sql)) {
if (mysqli_num_rows($result)> 0) {       
     while($rows = mysqli_fetch_assoc ($result)) {                      
        $id = $row['id'];
           blablablabla
        }
bothers me the most that I don't know the date comparison syntax
You seem to be looking for MySQL date function current_date(), which is the equivalent of php function call date("Y-m-d"):
SELECT * FROM users WHERE report_date >= current_date;
Side note: do not surround the column names with single quotes, otherwise it turns it to a literal string, so you end up comparing string 'report_date' with the date, which will not do what you want. Same goes for the table name, that should not be single quoted either.

Merge two SQL queries together (syntax issue)

I'm using PHP to send this query where lastConn is a datetime object.
$result = $mysqli->query("SELECT id, username, lastConn FROM users LIMIT $startIndex, 50") or die($mysqli->error);
However my goal is not to get the raw lastConn data, but the time difference between lastConn and CURRENT_TIMESTAMP. I wrote this query which does the job :
SELECT TIMESTAMPDIFF(MINUTE,lastConn,CURRENT_TIMESTAMP) AS 'duration' FROM users;
I'm now trying to merge these two queries together to get the time difference in the first query but I can't seem to find the correct syntax.
Here is how I'm retrieving the data after performing the query using PHP:
while($row = $result->fetch_assoc()){
echo $row['id'];
echo $row['username'];
echo $row['lastConn']; //should echo the time difference instead of the raw lastConn value
}
How can I directly get the time difference between lastConn and CURRENT_TIMESTAMP in my first query, without having to use a second one ?
you could probably just add the portion of your second query to the first, like this below. you had it all working, just needed that last step!
$mysqli->query("SELECT id, username, lastConn, TIMESTAMPDIFF(MINUTE,lastConn,CURRENT_TIMESTAMP) AS 'duration' FROM users LIMIT $startIndex, 50")
hope this helps.

Basic php - echo mysql, how?

I want it to echo how many posts there are in bestallt where its ID is 1 from the table order and display it as how many posts there are in numbers. I am connected to the database in the PHP file, that's not an issue. I'm just not sure how to put it all down in PHP, quite new to this. I just can't get it to echo what I want, nothing comes out/I get an error.
Any help is appreciated!
Your present code does not fetch the data from the database, it simply echoes the SQL query you have written.
Quite a lot more code goes in to fetching results from a mysql database, and I am not sure reproducing a full explanation here will serve anyone's interests. However, you may wish to view the examples of how to use PDO (a method of using mysql databases from php) here, and then either edit or re-ask your question if you find you have specific difficulties following those examples.
Try this code:
<td>
<?php
$sql = "SELECT count(*) FROM order WHERE bestallt='1'"; // Your SQL query
$response = mysql_query($sql);
if (mysql_num_rows($response) == 0) {
// Your query returned 0 rows!
}
while($row = mysql_fetch_array($response)){
// For each row returned from your query
// $row is an array
// For example, You can use it:
echo $row['data1'];
echo $row['data2'];
echo $row['data3'];
// data1, data2, data3 are the name of the fiels in your database
}
?>
</td>
Have a nice day!
Try this,
$sql = "SELECT count(*) FROM order WHERE bestallt='1'"
$res=mysql_query($sql);
$arr=mysql_fetch_array($res);
echo "<pre>";print_r($arr); //you will get whole array for matching record of your order table if found anything
To learn more, you can check my earlier Answer: how generate report between the two dates using datepicker,ajax,php,mysql.?
In that answer I have described whole working demo.

PHP Mysql Query with Time Interval

I have a php that extracts information from a mysql database just fine, however when I tried to add the functionality to check for data depending on an interval I am not getting any data from the database, just replies with an empty result. When I run it in Phpmyadmin it works just fine. Here's the code:
$result = mysql_query("
SELECT * FROM SensorLog
WHERE (SensorTag='$requestedSensor' and TimeEntered<'$end'
and TimeEntered>'$start');
") or die(mysql_error());
start and end are of the form: 2014-01-22 15:36:37 just like my timestamped column in the database.
What am I doing wrong here? I assume something is wrong with the query but I can't figure out what.
Same can be achieved using BETWEEN clause as follows:
$result = mysql_query("SELECT * FROM SensorLog
WHERE (SensorTag='$requestedSensor' and TimeEntered BETWEEN '$end' AND '$start')") or die(mysql_error());
If date start and date end have the same value, the query should be TimeEntered >= $start and TimeEntered <= $end

Getting minute difference between two timestamps in mysql using TIMESTAMPDIFF

I have my SQL statement like this trying to get the difference in 2 timestamps greater than 10 minutes. "timestamp" is a column in MYSQL which I hold a timstamp as such "1365793346"
SELECT * FROM table WHERE TIMESTAMPDIFF(MINUTE,timestamp,NOW()) AS thisisit
Im not sure if using "AS thisisit" is a current function of TIMESTAMPDIFF but I was able to find some old posts that how it used as such. I am not sure if its supported anymore because I an a syntax error at "AS thisisit"
I have also tried using
SELECT * FROM table WHERE TIMESTAMPDIFF(MINUTE,timestamp,NOW()) > 10
Where I am not sure what is going on is first is my syntax correct and second how to do associate this query with a label so I can echo it. My full PhP code looks like this
SELECT * FROM table WHERE TIMESTAMPDIFF(MINUTE,timestamp,NOW()) > 10
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row[0];
}
I was assuming I could use something like this to echo the results, but I get nothing to the screen. Can anyone point me in the right direction?
echo $row[0];
AS thisisit in this case have to be used to set an alias to your column.
So, you should use the following:
SELECT timestamp AS 'thisisit'
FROM table
WHERE TIMESTAMPDIFF(MINUTE, timestamp, NOW()) > 10;

Categories