Comparing two dates in a SQL request - php

I am a beginner in PHP and Javascript, so I'm struggling to compare two dates in a SELECT request like this:
<?php
require 'db.php';
$sql = "SELECT * FROM shortcode WHERE invalid_from_shortcode < Date()";
$result = pg_query($sql);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
?>
I'm trying to select only the 'shortcodes' where the [invalid_from_shortcode] column is inferior from the current date.
I don't know how to get the current date and whether the structure is correct.

<?php
require 'db.php';
$sql = "SELECT * FROM shortcode WHERE invalid_from_shortcode < NOW()";
$result = pg_query($sql);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
?>
Date() is a php function. in Mysql/PostgreSQL you must use NOW()

...
$sql = "SELECT * FROM shortcode WHERE invalid_from_shortcode < Date()";
...
A PHP functions like Date() is not visible in the SQL string. Either pass a value or use an equivalent Postgres function, like #pr1nc3 already suggested.
However, while you do not disclose the actual data type of invalid_from_shortcode it's unclear whether now() can serve as equivalent function. It returns the current timestamp with time zone, which is meaningfully different from the current date - effectively equivalent to the current timestamptz truncated to 00:00 according to the current timezone setting. You might need CURRENT_DATE (same as now()::date) instead. Related:
Select today's (since midnight) timestamps only
Aside: Unlike two other answers suggested, there is no CURDATE() in Postgres. That probably confusing MySQL with Postgres.

You want to use NOW() not DATE().

May be you are looking for CURDATE() .
$sql = "SELECT * FROM shortcode WHERE DATE(invalid_from_shortcode) < CURDATE()";

You should be using NOW() function instead of date() and you need to convert the date in a suitable format enter link description here you can visit this link for converting the date format

use
NOW() Returns the current date and time

Related

get all today's event where the date is stored as int

i need help on this code..Im a newbie on this thing
i would like to query a table to get all today's event where the date&time is stored as int (eg: 1510876800)
i tried it like this
$time = time();
$changedate=date("Y-m-d", strval($time));
$today=strtotime($changedate);
$sql = "SELECT * FROM " . $xoopsDB->prefix('extcal_event') . " WHERE event_start='$today' ORDER BY event_organisateur ASC";
its not working because of the date in event_start have different time
How do i solve this ?
You are comparing unix timestamps so that will only match on the exact same second of that specific day.
If you have a unix timestamp stored, first you need to convert it to a mysql datetime value and then you can get the date part of it:
... WHERE DATE(FROM_UNIXTIME(event_start)) = :today ...
Here the value you bind to :today should have the Y-m-d format.
Note that I have used a placeholder for your variable as you should use prepared statements instead of injecting values directly into your query.

Mysql Get table result between two dates

I know my question is similar to other question already answered but my issue is different because I need some alternative or advice no how to go the other way around.
My issue is: I want to get values between either two dates or one according to what user wants..
When User request data of one day.. php query data successful.. but problem is when data requested is between two dates..
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '$first_date' AND
`meta_transaction_date` <= '$second_date' ");
return $query->result();
I get an empty set...
So I thought may be the values are not submitted correct.. so I echoed the values to see if they are correct or not. I find they are correct...
$first_date = 09/13/2014;
$second_date = 09/19/2014;
But if I try to put the value like
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '09/13/2014' AND
`meta_transaction_date` <= '09/19/2014' ");
return $query->result();
I get my result back correct.. so is there anything am doing it wrong??
Change the type of meta_transaction_date to DATE as that is what it is! Also use the standard 'yyyy-mm-dd' when passing in DATEs.
Your problem probably stems from string ordering of the 'mm/dd/yyyy' US date format which is horrible for coding. If you wish to display the DATE in this format, convert it when SELECTing the final output.
MySQL has a built in function called Between that you can use like this:
SELECT * FROM table_name WHERE date_column BETWEEN 'start_date_parameter' AND 'end_time_parameter'
Try to cast the date first , and then with between statement:
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` BETWEEN
date_format(str_to_date('$first_date', '%d/%m/%Y'), '%Y-%m-%d') AND
date_format(str_to_date('$second_date', '%d/%m/%Y'), '%Y-%m-%d')");
$query = $this->db->query("SELECT * FROM `meta_receipt_data`
WHERE `meta_transaction_date` >= '09/13/2014'
AND `meta_transaction_date` <= '09/19/2014' ");
Since the above seems to be working fine, the problem is in your code.
$query = $this->db->query("SELECT `meta_transaction_date` FROM meta_receipt_data WHERE
meta_transaction_date BETWEEN "
.date( "Y-M-d", ( strtotime($first_date) ) )." AND "
.date( "Y-M-d", ( strtotime($second_date) ) ) );
A word of advice, do not use queries like SELECT * as they will degrade performance of your application. And I just read in your comment to your own question:
I have set the type as Varchar
Do not do that. It is best to use the DATE type to store dates. You can use the query:
ALTER TABLE `meta_receipt_data`
MODIFY `meta_transaction_date` DATE NOT NULL;`
Well, that is assuming you wish to keep the column to not accept null values.
I found that the value had space before and after so I use $first = trim($first_date); and problem solved...

use the like command in MySQLi and php for a datetime field

I am attempting to run a query based on a date to get everything changed today, however the field that has the date is a datetime field, which I can't change. The value in my date_modified field looks like 2013-10-25 07:05:43. I know the query works without the date. If I just use Navicat and run the query's where clause as:
WHERE inventory.date_modified like '2013-10-25%'
It runs fine. I found a few ideas in other SO posts and when I try to put it into my php code as:
$today = date("Y-m-d"); $today = '%' . $today . '%';
and then my where clause is:
WHERE inventory.date_modified like $today
I get the fatal error of trying to parse a non object. I know there is a value in $today, but I am unclear how to do this with my php code?
Best solution was the N.B.'s in the question comment. Because, if you have index on field date_modified, it will be used.
So, if you have date formated as Y-m-d, like you have in $today, you can do:
$sql = "
...
WHERE inventory.date_modified BETWEEN '$today 00:00:00' AND '$today 23:59:59'
...
";
Another example would be, to use DATE() function, to get date part from datetime:
$sql = "
...
WHERE DATE(inventory.date_modified) = '$today'
...
";
but, this example is not good if you have index on field date_modified, because it will be ignored, and whole table will be scanned.
You Forget to set the quotes on database value:
WHERE inventory.date_modified like '$today'
Try this code:-
$today = '2013-10-25';
SELECT * FROM inventory WHERE DATE_FORMAT(inventory.date_modified, "%Y-%m-%d") = $today;

MySQL 'Between' dates not selecting the correct results using PHP (and Codeigniter)

Here is my code (using CodeIgniter):
$now = date('Y-m-d');
$then = strtotime($now . '-1 week');
$then = date('Y-m-d', $then);
$q3 = $this->db->query("SELECT *
FROM posts
WHERE publish_date BETWEEN '$then' AND '$now'");
$data['posts_today'] = $q3->num_rows();
I clearly have posted at least twenty posts this week, but it only displays '1'. Any ideas why?
Thanks!
Does this work for you:
$q3 = $this->db->query("SELECT *
FROM posts
WHERE publish_date BETWEEN DATE_SUB(NOW(), INTERVAL 1 WEEK)
AND NOW()");
Potential issues I see:
is POSTS.publish_date a DATETIME data type?
if PHP and MySQL are on different hosts, NOW from codeigniter/PHP could be a different time than what's being stored/used in MySQL.
Verify that MySQL expects dates in that format. You might be better off using MySQL's date functions to compose them.
First, offload everything you can to MySQL. The less date math you have to do the better.
Second, Look at what your actual created code looks like. Change this
$q3 = $this->db->query("SELECT *
FROM posts
WHERE publish_date BETWEEN '$then' AND '$now'");
to this
$sql = "SELECT *
FROM posts
WHERE publish_date BETWEEN '$then' AND '$now'");
print "EXECUTING: $sql\n";
$q3 = $this->db->query( $sql );
You're assuming that the SQL you are generating is valid, and it might not be. This is very common when you're using one language to generate code in another. Always print to verify your assumptions.

how to display all the possible data greater than the current date

$Date = date("m/d/Y");
$result = mysql_query("SELECT * FROM service WHERE SType = 'Retreat' and Start_date > '$Date' ");
Start_date format is m/d/y also.
whats wrong with my code? all i want to do is to display all the possible data greater than the current date. but it always show all the data from the database.
Use date("Y-m-d") rather than date("m/d/Y").
It depends on how you store your date. If its stored as a unixtime, then you simply do an equal or greater check and you are on your way.
PHP has some great functions to turn date into unixtime. Like strtotime
It's best if you use the YYYY-MM-DD format for dates in MySQL.
Have you looked at this: http://www.bigroom.co.uk/blog/dates-in-php-and-mysql ?
The article suggests you consider doing something like
$result = mysql_query(
"SELECT * FROM service WHERE SType = 'Retreat' and Start_date > FROM_UNIXTIME($Date)"
);

Categories