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

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.

Related

PHP and MYSQL Find Records Based on Date

I have been trying to pull records based on a specified date. In the DB I have a column where I store unix timestamps. The user has the option to select records based on a date. The user inputs: 08/08/2016 (for example)
How would I write my SQL statement to handle this?
$query .= "`".$o."` = '".date("Y-m-d",strtotime($v))."' AND ";
Here we see the line where part of the SQL statement is built, because more than one column could be targeted by the user during their search request.
Somehow I need to be able to turn $o (which is a column storing unix timestamps) into the Y-m-d format for comparison, as shown above and make this work in an SQL statement.
Any help would be appreciated.
EDIT
Here is what worked for me:
$query .= "".$o.">= '".strtotime($v)."' AND".$o."< '".(strtotime($v)+(24*60*60))."' AND ";
You can do something like:
"WHERE DATE(`$o`) = '".date("Y-m-d",strtotime($v))."'"
However this won't use indexes, so if you have a large table it will be slower. If you want to be able to use indexes you can do:
"WHERE `$o` >= ".date("Y-m-d",strtotime($v))."
AND `$o` < ".date("Y-m-d",strtotime($v))." + INTERVAL 1 DAY"
You can also try this approach and use UNIX_TIMESTAMP on MySQL.
$v = '2016-08-04';
$query .= "'".$o."' = UNIX_TIMESTAMP('$v') AND ";

Multiple MYSQL Statements executed as a single statement

I've got a bit of a problem with my code. I'm sure that it is something simple, but I just can't figure it out! I have been on tons of forums and have read several books... but every answer that I have worked to has failed. I almost guarantee that it's the way that I am using my syntax (and yes I know... procedural PHP is not really used anymore) but I am really a bit of a newbie to this and I am just trying to pick up the basics before moving onto OOP and PDO connections.
Could you please help me? At the moment I can get the user to select their date from the date picker and the results specifically from that date only will return... only problem is that the event is displaying the event_id as opposed to the name of the event that it relates to (1 = 5km run) for example.
Somehow I need to access the events table and pull the row that relates to that specific event_id.
I have normalized my database, and according to my tutor it looks ok. To give you an idea what it looks like - logins table (all user logins details), results table (a history of submitted events) events table (the events themselves).
On the results table the foreign keys are logins_id and the event_id. The primary key is the results_id in the results table and the only data stored here is the time and data (individual columns).
<?php // -----Stage 1. On submission of the form run the following -----//
if (isset($_POST['submit_d'])) {
$mydate = $_POST ['MyDate'];
$my = preg_replace('/[^a-zA-Z0-9]+/', ' ', $mydate);
if ($mydate) {
$result = mysql_query("SELECT * FROM logins WHERE username = '$username' LIMIT 1");
//This function will take the above query and create an array...
while($row = mysql_fetch_array($result))
{
//With the array created above, I can create variables (left) with the outputted array (right)
$logins_id3 = $row['logins_id'];
}
$sql = "SELECT * FROM results where $logins_id3 AND date = $mydate ";
/* ----- Here is the code that I want to use in conjunction with the above statement --->
$query = "SELECT logins.username,events.event,results.time,results.date,logins.age,logins.gender
FROM logins INNER JOIN results ON logins.logins_id=results.logins_id INNER JOIN events ON results.event_id=events.event_id
ORDER BY time ASC LIMIT 10";
*/
$resultz = mysql_query($sql);
if( mysql_num_rows($resultz) ) {
while ($row = mysql_fetch_array($resultz)) {
echo "<table><tr><th>Username</th><th>Event</th><th>Time (HH:MM:SS)</th><th>Date (YY/MM/DD)</th><th>Age</th><th>Gender</th>
</tr><tr><td>".$username."</td>"
."<td>".$row['event_id']."</td>"."<td>".$row['time']."</td>"." <td>".$row['date']."</td>"."<td>".$row['age']."</td>".
"<td>" $row['gender']."</td></tr></table>";
}
}
}
}
?>
The other thing I would like to do.. although this is not crucial, is to strip special characters from the input. Basically I'm using a jquery calendar picker and I want the user to be able to select their date in the 2014-05-26 format and the php to remove the - before it is submitted to the database, that way it doesn't effect the users experience but it will work with my current code.
Anyways sorry to waffle on, any help on either of these matters would be much appreciated!
Yours Sincerely:
Peter Scales.
You can use a join to get the data that relates to the event ID:
SELECT * FROM results r LEFT JOIN events e ON r.event_id = e.event_id WHERE ...
You can then select where "e.event_id = $event_id"; and the rest of your query logic.
You can also filter out any unwanted characters by using preg_replace: http://ar2.php.net/preg_replace

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;

Compare string datatype to a date datatype PHP MYSQL

In my MySQL database, I have this Time data type as one of my values: 06:00:00. I have the following query that checks the time as one of the conditions that has to be satisfied
$time = "06:00:00";
$getdetails=SELECT First_Name, Last_Name, EMAIL
FROM parents
WHERE Email_Receive_Time = $time;
$results=mysql_query($getdetails);
However I do not get any results. On further research I have seen that it is because I am comparing a STRING type value ($time) to a TIME type value (value in my database). Is there a way i can compare the two without changing my database structure to a varchar? All help will be appreciated.
MySQL is perfectly capable of comparing a string to a TIME value. You just need to have the proper query syntax. In your case, you need to quote the comparison value:
$time = "06:00:00";
$getdetails = "SELECT First_Name, Last_Name, EMAIL
FROM parents
WHERE Email_Receive_Time = '$time'";
$results=mysql_query($getdetails);
And if it is user-supplied, well you should escape it.
You are wrong.
Your mistake is much simpler, it has nothing to do with data formats, but with query format.
Ask yourself what does mean 06:00:00 in terms of SQL syntax.
Btw, running query this way will help you A LOT:
$results=mysql_query($getdetails) or trigger_error(mysql_error()." in ".$getdetails);
always run all your queries this way and get in touch with every error occurred
This will work when comparing against TIME type of field:
To compare against DATETIME or TIMESTAMP, I'd suggest running the $time variable through strotime() first.
$time = "06:00:00";
$getdetails = "SELECT First_Name,
Last_Name,
EMAIL
FROM parents
WHERE Email_Receive_Time = '$time'";
$results = mysql_query($getdetails);
Try using STR_TO_DATE function, it should work for you.
Thanks
Ravi Mudaliar

php mysql date/time question

I've built a small application which has User Management, a frontend console to enter data and a backend console to control parts of the frontend. The frontend adds rows to a MySQL database which are timestamped. The backend needs to be able to select rows from the database between X and Y dates.
Everything works so far, except the date part which I'm really struggling with.
The frontend SQL input looks like this (simplified with spurious code removed):
$date = time();
$top_level_category = $_POST['top_level_category'];
$sub_level_category = $_POST['sub_level_category'];
$company = $_POST['company'];
$agent_name = $_POST['agent_name'];
$ticket_id = $_POST['ticket_id'];
$sql = "INSERT INTO dacc_data ("
. "id, top_level_category, sub_level_category, "
. "agent_name, date, ticket_id, company"
. ") VALUES ("
. "NULL, '$top_level_category', '$sub_level_category', "
. "'$agent_name', FROM_UNIXTIME('$date'), '$ticket_id', '$company'"
. ")"
;
$result = mysql_query($sql) or die (mysql_error());
That seems to work ok, the timestamp is being picked up and added to a DATETIME column in my table. It displays as dd/mm/yyyy hh:mm:ss within the database.
So ... my first question is - is this the right way to do it?
The second question being, what sort of SQL statement would I need to pull out an array of rows between X and Y date.
Apologies if this is rambling a bit, hope it's clear but if you need more information let me know.
MySQL datetime should be formatted with dashes:
YYYY-MM-DD HH:MM:SS
http://dev.mysql.com/doc/refman/5.0/en/datetime.html
Then you can query for date ranges a couple of ways:
select *
from table
where date >= '[start date]' and date <= '[end date]';
or
select *
from table
where date between '[start date]' and '[end date]';
where "table" is the name of your database table and "date" is the name of your datetime field.
You are correct. I can confirm that the Database has "YYYY-MM-DD HH:MM:SS" - I am using SQLWave editor for browsing the DB quickly, it auto-formats the DATETIME column.
// Initial questions still stand :)
Or not, just noticed you updated the answer - thank you very much! I had actually tried that very same query several times to no avail, mainly because my WHERE was specifying the date format incorrectly. Misled by SQLWave :(
Back to using command line from now on !!!
"what sort of SQL statement would I need to pull out an array of rows between X and Y date?"
SELECT * FROM `dacc_data` where `date` between "2008-11-01" and "2008-12-01"

Categories