php ORA-01861: literal does not match format string - php

I'm writing a php script to insert data into an Oracle database, and I'm getting ORA-01861: literal does not match format string when I try to run it. It has something to do with the date and they way it's calculated, but I'm not sure how/where to fix it. In the table, the log_date is type date. Below is the section of code that I'm working with for the date after I've already established the db connection. Does it need to go in my $query definition?
$ticks = $mnemonic->timestamp . "\n";
$seconds = ($ticks - 621355968000000000) / 10000000;
$day = date("Y-m-d H:i:s", $seconds);
$query = "INSERT into TLM_Item(log_date) Values('$day')";
$updt = ociparse($conn, $query);
if(!$updt){
print "No query \n";
exit;
}
$r = ociexecute($updt , OCI_COMMIT_ON_SUCCESS);

Oracles default date format is not YYYY-MM-DD. Fortunately, though, Oracle supports the keyword DATE so support dates. I haven't used it in this context, but it should work:
$query = "INSERT into TLM_Item(log_date) Values (DATE '$day')";
Alternatively, you could use the built-in function to_date():
$query = "INSERT into TLM_Item(log_date) SELECT to_date('$day', 'YYYY-MM-DD HH24:MI:SS') FROM DUAL";

Related

Store a 'best before' date in SQL Database [duplicate]

I'm using jQuery datepicker
the format of the datepicker is this 08/25/2012
I have errors when inserting to my database it inserts only 0000-00-00 00 00 00
My code is:
<?php
$id = $_POST['id'];
$name = $_POST['name'];
$date = $_POST['date'];
$sql = mysql_query( "INSERT INTO user_date VALUE( '', '$name', '$date')" ) or die ( mysql_error() );
echo 'insert successful';
?>
I'm sure my insert is correct.
As stated in Date and Time Literals:
MySQL recognizes DATE values in these formats:
As a string in either 'YYYY-MM-DD' or 'YY-MM-DD' format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example, '2012-12-31', '2012/12/31', '2012^12^31', and '2012#12#31' are equivalent.
As a string with no delimiters in either 'YYYYMMDD' or 'YYMMDD' format, provided that the string makes sense as a date. For example, '20070523' and '070523' are interpreted as '2007-05-23', but '071332' is illegal (it has nonsensical month and day parts) and becomes '0000-00-00'.
As a number in either YYYYMMDD or YYMMDD format, provided that the number makes sense as a date. For example, 19830905 and 830905 are interpreted as '1983-09-05'.
Therefore, the string '08/25/2012' is not a valid MySQL date literal. You have four options (in some vague order of preference, without any further information of your requirements):
Configure Datepicker to provide dates in a supported format using an altField together with its altFormat option:
<input type="hidden" id="actualDate" name="actualDate"/>
$( "selector" ).datepicker({
altField : "#actualDate"
altFormat: "yyyy-mm-dd"
});
Or, if you're happy for users to see the date in YYYY-MM-DD format, simply set the dateFormat option instead:
$( "selector" ).datepicker({
dateFormat: "yyyy-mm-dd"
});
Use MySQL's STR_TO_DATE() function to convert the string:
INSERT INTO user_date VALUES ('', '$name', STR_TO_DATE('$date', '%m/%d/%Y'))
Convert the string received from jQuery into something that PHP understands as a date, such as a DateTime object:
$dt = \DateTime::createFromFormat('m/d/Y', $_POST['date']);
and then either:
obtain a suitable formatted string:
$date = $dt->format('Y-m-d');
obtain the UNIX timestamp:
$timestamp = $dt->getTimestamp();
which is then passed directly to MySQL's FROM_UNIXTIME() function:
INSERT INTO user_date VALUES ('', '$name', FROM_UNIXTIME($timestamp))
Manually manipulate the string into a valid literal:
$parts = explode('/', $_POST['date']);
$date = "$parts[2]-$parts[0]-$parts[1]";
Warning
Your code is vulnerable to SQL injection. You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
Also, as stated in the introduction to the PHP manual chapter on the mysql_* functions:
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
You appear to be using either a DATETIME or TIMESTAMP column for holding a date value; I recommend you consider using MySQL's DATE type instead. As explained in The DATE, DATETIME, and TIMESTAMP Types:
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
You should consider creating a timestamp from that date witk mktime()
eg:
$date = explode('/', $_POST['date']);
$time = mktime(0,0,0,$date[0],$date[1],$date[2]);
$mysqldate = date( 'Y-m-d H:i:s', $time );
$date_field = date('Y-m-d',strtotime($_POST['date_field']));
$sql = mysql_query("INSERT INTO user_date (column_name,column_name,column_name) VALUES('',$name,$date_field)") or die (mysql_error());
You must make sure that the date format is YYYY-MM-DD on your jQuery output. I can see jQuery returns MM-DD-YYYY, which is not the valid MySQL date format and this is why it returns an error.
To convert it to the right one you could do this:
$dateFormated = split('/', $date);
$date = $dateFormated[2].'-'.$dateFormated[0].'-'.$dateFormated[1];
Then you will get formatted date that will be valid MySQL format, which is YYYY-MM-DD, i.e. 2012-08-25
I would also recommend using mysql_real_escape_string as you insert data into database to prevent SQL injections as a quick solution or better use PDO or MySQLi.
Your insert query using mysql_real_escape_string should rather look like this:
$sql = mysql_query( "INSERT INTO user_date VALUE( '', '" .mysql_real_escape_string($name). "', '" .mysql_real_escape_string($date). "'" ) or die ( mysql_error() );
Get a date object from the jquery date picker using
var myDate = $('element').datepicker('getDate')
For mysql the date needs to be in the proper format. One option which handles any timezone issues is to use moment.js
moment(myDate).format('YYYY-MM-DD HH:mm:ss')
The simplest method is
$dateArray = explode('/', $_POST['date']);
$date = $dateArray[2].'-'.$dateArray[0].'-'.$dateArray[1];
$sql = mysql_query("INSERT INTO user_date (column,column,column) VALUES('',$name,$date)") or die (mysql_error());
HTML:
<div class="form-group">
<label for="pt_date" class="col-2 col-form-label">Date</label>
<input class="form-control" type="date" value=<?php echo date("Y-m-d") ;?> id="pt_date" name="pt_date">
</div>
SQL
$pt_date = $_POST['pt_date'];
$sql = "INSERT INTO `table` ( `pt_date`) VALUES ( '$pt_date')";
Suppose you receive a Christmas date:
December 25, 2021 (25 de Diciembre del año 2021) in string format: "d-m-Y" for example "12-25-2021". First create a valid DateTime object from the received format:
var_dump(DateTime::createFromFormat("d-m-Y","25-12-2021", new DateTimeZone("America/Argentina/Buenos_Aires")));
This generates as output:
object(DateTime)#2 (3) {
["date"]=>
string(26) "2021-12-25 10:21:11.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(30) "America/Argentina/Buenos_Aires"
}
Now to get the date field from the DateTime object ready to go using format("Y-m-d H:i:s")):
var_dump(DateTime::createFromFormat("d-m-Y","25-12-2021",new DateTimeZone("America/Argentina/Buenos_Aires"))->format("Y-m-d H:i:s"));
This generates as output a ready to insert value:
string(19) "2021-12-25 10:56:30"
In summary now you can insert a formated date ('DD-MM-YYYY') in MySQL like this:
<?php
//string input post like "25-12-2021"
$date_input = $_POST['date_input'];
//create DateTime object
$date_time_obj=DateTime::createFromFormat("d-m-Y","25-12-2021",new DateTimeZone("America/Argentina/Buenos_Aires"));
//format date ready to insert as string at MySQL
$str_date=$date_time_obj->format("Y-m-d H:i:s");
?>
Now run directly from PHP to MySQL as a query:
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
//verify connection
if (mysqli_connect_errno()) {
printf("Error de conexión: %s\n", mysqli_connect_error());
exit();
}
//prepare the query to execute
$stmt = $mysqli->prepare("INSERT INTO table_example (DATE_FIELD) VALUES (?)");
//prevent sql injection
$stmt->bind_param('s', $str_date);
//execute prepared statements
$stmt->execute ();
?>
These days, I am not good with dates. Thanks to the following work, I can print the dates in the format I want.
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$scr = strtotime($year . '-' . $month . '-' . $day);
$gelis_tarihi = date('Y-m-d', $scr);
$yil = $_POST['yil'];
$ay = $_POST['ay'];
$gun = $_POST['gun'];
$birlestir = strtotime($yil . '-' . $ay . '-' . $gun);
$gelis_tarihi = date('Y-m-d', $birlestir);
Try Something like this..
echo "The time is " . date("2:50:20");
$d=strtotime("3.00pm july 28 2014");
echo "Created date is " . date("d-m-y h:i:sa",$d);
First of all store $date=$_POST['your date field name'];
insert into **Your_Table Name** values('$date',**other fields**);
You must contain date in single cote (' ')
I hope it is helps.

Error saving datetime to database after clicking buy on DoExpressCheckout

My problem is the following:
When DoExpressCheckout() is executed i have to save some data to Database, including the current time + X time
The type of the field of the database is set to "datetime"
I'm using the strtotime function in this way
date_default_timezone_set('Europe/Rome');
$currentTime = date("Y-m-d");
$expected = date('Y-m-d',strtotime($currentTime.'+ 7 days'));
echo $expected;
$sql = "INSERT INTO acquisti (durata,prezzi,expectedtime) VALUES (".$str.",".$resArray['AMT'].",".$expected.")";
echo $sql;
mysql_query($sql) or die("Errore di inserimento");
Here i have two problems:
1) The query always returns me error when putting the $expected variable into the expectedtime field
2) If i put it manually (just to try if i was stupid) it writes me 0000-00-00 (i've enabled the ALLOW_INVALID_DATES)
Any suggestions?
Thanks a lot
Your field type is 'datetime', but you are only sending date using the INSERT query.
You need to use date('Y-m-d H:i:s') instead of date('Y-m-d'), or if you need only the date change the type of the field to date.
Put values in enclosure:
$sql = "
INSERT INTO acquisti (
durata, prezzi, expectedtime
) VALUES (
'$str', '{$resArray['AMT']}', '$expected'
)
";
But you should really need to start using prepared statements.
If you wish to pass datetime, then you should format accordinaly, like Y-m-d H:i:s.
PHP example:
$expected = date_create('now')->modify('+7 day')->format('Y-m-d H:i:s');
MySQL example:
$sql = "
INSERT INTO acquisti (
durata, prezzi, expectedtime
) VALUES (
'$str', '{$resArray['AMT']}', DATE_ADD(NOW(), INTERVAL 7 DAY)
)
";

Failing to compare php date with mysql date

Got stuck in a complex or maybe stupid problem. I am getting a query from mysql, and then trying to compare a date column with a PHP data which i formatted to the same format i.e "Y-m-d" it always results in no match, although i see there is a match.. and it gets the right result set too.
<?php
date_default_timezone_set('America/Los_Angeles'); // set timezone to our timezone
$constantTime = time(); // get value of time in constant
$appDate = date("Y-m-d", $constantTime); //that defines php time variable -
$queryDate = "SELECT * FROM date WHERE date='$appDate'";
$resultDate = mysql_query($queryDate) or die("Sorry Website Under Maintainence");
$recordDate = mysql_fetch_array($resulDate);
if ($appDate == date("Y-m-d", strtotime($recordDate['date']))) {
echo "MATCH ";
$dateID = $recordDate['dateID'];
} else {
mysql_query("insert into date(date) values('$appDate')")or die("Database write error1");
$resultDate = mysql_query($queryDate) or die("Sorry Website Under Maintainence");
$recordDate = mysql_fetch_array($resultDate);
echo "NO MATCH ";
$dateID = $recordDate['dateID'];
}
This is always triggering the else, i tried === instead of ==, i tried strcmp
As i assume you're comparing datetime field, you have two possibilities:
Cast field to date:
$queryDate = "SELECT * FROM your_table WHERE date(your_date_field) = date('$appDate')";
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date
or
Modify your date format to be ISO compatible:
$appDate = date("Y-m-d H:i:s", $constantTime); //it defines date in format 2015-03-14 15:00:00
$queryDate = "SELECT * FROM your_table WHERE your_date_field='$appDate'";
See also this question

PHP mysql insert date format

I'm using jQuery datepicker
the format of the datepicker is this 08/25/2012
I have errors when inserting to my database it inserts only 0000-00-00 00 00 00
My code is:
<?php
$id = $_POST['id'];
$name = $_POST['name'];
$date = $_POST['date'];
$sql = mysql_query( "INSERT INTO user_date VALUE( '', '$name', '$date')" ) or die ( mysql_error() );
echo 'insert successful';
?>
I'm sure my insert is correct.
As stated in Date and Time Literals:
MySQL recognizes DATE values in these formats:
As a string in either 'YYYY-MM-DD' or 'YY-MM-DD' format. A “relaxed” syntax is permitted: Any punctuation character may be used as the delimiter between date parts. For example, '2012-12-31', '2012/12/31', '2012^12^31', and '2012#12#31' are equivalent.
As a string with no delimiters in either 'YYYYMMDD' or 'YYMMDD' format, provided that the string makes sense as a date. For example, '20070523' and '070523' are interpreted as '2007-05-23', but '071332' is illegal (it has nonsensical month and day parts) and becomes '0000-00-00'.
As a number in either YYYYMMDD or YYMMDD format, provided that the number makes sense as a date. For example, 19830905 and 830905 are interpreted as '1983-09-05'.
Therefore, the string '08/25/2012' is not a valid MySQL date literal. You have four options (in some vague order of preference, without any further information of your requirements):
Configure Datepicker to provide dates in a supported format using an altField together with its altFormat option:
<input type="hidden" id="actualDate" name="actualDate"/>
$( "selector" ).datepicker({
altField : "#actualDate"
altFormat: "yyyy-mm-dd"
});
Or, if you're happy for users to see the date in YYYY-MM-DD format, simply set the dateFormat option instead:
$( "selector" ).datepicker({
dateFormat: "yyyy-mm-dd"
});
Use MySQL's STR_TO_DATE() function to convert the string:
INSERT INTO user_date VALUES ('', '$name', STR_TO_DATE('$date', '%m/%d/%Y'))
Convert the string received from jQuery into something that PHP understands as a date, such as a DateTime object:
$dt = \DateTime::createFromFormat('m/d/Y', $_POST['date']);
and then either:
obtain a suitable formatted string:
$date = $dt->format('Y-m-d');
obtain the UNIX timestamp:
$timestamp = $dt->getTimestamp();
which is then passed directly to MySQL's FROM_UNIXTIME() function:
INSERT INTO user_date VALUES ('', '$name', FROM_UNIXTIME($timestamp))
Manually manipulate the string into a valid literal:
$parts = explode('/', $_POST['date']);
$date = "$parts[2]-$parts[0]-$parts[1]";
Warning
Your code is vulnerable to SQL injection. You really should be using prepared statements, into which you pass your variables as parameters that do not get evaluated for SQL. If you don't know what I'm talking about, or how to fix it, read the story of Bobby Tables.
Also, as stated in the introduction to the PHP manual chapter on the mysql_* functions:
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
You appear to be using either a DATETIME or TIMESTAMP column for holding a date value; I recommend you consider using MySQL's DATE type instead. As explained in The DATE, DATETIME, and TIMESTAMP Types:
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
You should consider creating a timestamp from that date witk mktime()
eg:
$date = explode('/', $_POST['date']);
$time = mktime(0,0,0,$date[0],$date[1],$date[2]);
$mysqldate = date( 'Y-m-d H:i:s', $time );
$date_field = date('Y-m-d',strtotime($_POST['date_field']));
$sql = mysql_query("INSERT INTO user_date (column_name,column_name,column_name) VALUES('',$name,$date_field)") or die (mysql_error());
You must make sure that the date format is YYYY-MM-DD on your jQuery output. I can see jQuery returns MM-DD-YYYY, which is not the valid MySQL date format and this is why it returns an error.
To convert it to the right one you could do this:
$dateFormated = split('/', $date);
$date = $dateFormated[2].'-'.$dateFormated[0].'-'.$dateFormated[1];
Then you will get formatted date that will be valid MySQL format, which is YYYY-MM-DD, i.e. 2012-08-25
I would also recommend using mysql_real_escape_string as you insert data into database to prevent SQL injections as a quick solution or better use PDO or MySQLi.
Your insert query using mysql_real_escape_string should rather look like this:
$sql = mysql_query( "INSERT INTO user_date VALUE( '', '" .mysql_real_escape_string($name). "', '" .mysql_real_escape_string($date). "'" ) or die ( mysql_error() );
Get a date object from the jquery date picker using
var myDate = $('element').datepicker('getDate')
For mysql the date needs to be in the proper format. One option which handles any timezone issues is to use moment.js
moment(myDate).format('YYYY-MM-DD HH:mm:ss')
The simplest method is
$dateArray = explode('/', $_POST['date']);
$date = $dateArray[2].'-'.$dateArray[0].'-'.$dateArray[1];
$sql = mysql_query("INSERT INTO user_date (column,column,column) VALUES('',$name,$date)") or die (mysql_error());
HTML:
<div class="form-group">
<label for="pt_date" class="col-2 col-form-label">Date</label>
<input class="form-control" type="date" value=<?php echo date("Y-m-d") ;?> id="pt_date" name="pt_date">
</div>
SQL
$pt_date = $_POST['pt_date'];
$sql = "INSERT INTO `table` ( `pt_date`) VALUES ( '$pt_date')";
Suppose you receive a Christmas date:
December 25, 2021 (25 de Diciembre del año 2021) in string format: "d-m-Y" for example "12-25-2021". First create a valid DateTime object from the received format:
var_dump(DateTime::createFromFormat("d-m-Y","25-12-2021", new DateTimeZone("America/Argentina/Buenos_Aires")));
This generates as output:
object(DateTime)#2 (3) {
["date"]=>
string(26) "2021-12-25 10:21:11.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(30) "America/Argentina/Buenos_Aires"
}
Now to get the date field from the DateTime object ready to go using format("Y-m-d H:i:s")):
var_dump(DateTime::createFromFormat("d-m-Y","25-12-2021",new DateTimeZone("America/Argentina/Buenos_Aires"))->format("Y-m-d H:i:s"));
This generates as output a ready to insert value:
string(19) "2021-12-25 10:56:30"
In summary now you can insert a formated date ('DD-MM-YYYY') in MySQL like this:
<?php
//string input post like "25-12-2021"
$date_input = $_POST['date_input'];
//create DateTime object
$date_time_obj=DateTime::createFromFormat("d-m-Y","25-12-2021",new DateTimeZone("America/Argentina/Buenos_Aires"));
//format date ready to insert as string at MySQL
$str_date=$date_time_obj->format("Y-m-d H:i:s");
?>
Now run directly from PHP to MySQL as a query:
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
//verify connection
if (mysqli_connect_errno()) {
printf("Error de conexión: %s\n", mysqli_connect_error());
exit();
}
//prepare the query to execute
$stmt = $mysqli->prepare("INSERT INTO table_example (DATE_FIELD) VALUES (?)");
//prevent sql injection
$stmt->bind_param('s', $str_date);
//execute prepared statements
$stmt->execute ();
?>
These days, I am not good with dates. Thanks to the following work, I can print the dates in the format I want.
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$scr = strtotime($year . '-' . $month . '-' . $day);
$gelis_tarihi = date('Y-m-d', $scr);
$yil = $_POST['yil'];
$ay = $_POST['ay'];
$gun = $_POST['gun'];
$birlestir = strtotime($yil . '-' . $ay . '-' . $gun);
$gelis_tarihi = date('Y-m-d', $birlestir);
Try Something like this..
echo "The time is " . date("2:50:20");
$d=strtotime("3.00pm july 28 2014");
echo "Created date is " . date("d-m-y h:i:sa",$d);
First of all store $date=$_POST['your date field name'];
insert into **Your_Table Name** values('$date',**other fields**);
You must contain date in single cote (' ')
I hope it is helps.

Search between dates (date as VARCHAR)

I have several dates stored as varchar in the following format: 01-01-2012
I want to search between dates, but sadly it isn't working as I expected. I looked for other threads which have the same question (kinda), but the answers provided there didn't work for me.
Here is my code:
$fromday = $_POST['fromday'];
$frommonth = $_POST['frommonth'];
$fromyear = $_POST['fromyear'];
$tillday = $_POST['tillday'];
$tillmonth = $_POST['tillmonth'];
$tillyear = $_POST['tillyear'];
$vanaf = "$fromday-$frommonth-$fromyear";
$tot = "$tillday-$tillmonth-$tillyear";
// zoeken
$sel = "SELECT * FROM bestelling WHERE verzenddatum >= '$vanaf' AND verzenddatum <= '$tot'";
$dosel = mysql_query($sel) or die(mysql_error());
while($row = mysql_fetch_assoc($dosel))
{
$datum = $row['verzenddatum'];
echo $datum;
}
Please let me know what I'm doing wrong!
It is not returning any rows because the query is not doing the comparison on valid DATE or DATETIME fields. You should be storing the dates as a DATE type, but what you could do is this:
// Switch the order of date elements:
$vanaf = mysql_real_escape_string("$fromyear-$frommonth-$fromday");
$tot = mysql_real_escape_string("$tillyear-$tillmonth-$tillday");
$sel = "SELECT * FROM bestelling WHERE STR_TO_DATE(verzenddatum, '%d-%m-%Y') BETWEEN '$vanaf' AND 'tot'";
The mysql_real_escape_string() function simply reduces the risk of SQL injection, which is what your original code was vulnerable to.
The MySQL function STR_TO_DATE() converts a string to a valid MySQLDATE type. %d-%m-%Y is the format you have in your varchar string currently, but STR_TO_DATE converts it to '%Y-%m-%d' which MySQL can then use to make range comparisons.
Also, I'm using the BETWEEN syntax in the SQL as it is the same thing as val >= val1 AND val <= val2. It's just clearer and simpler: val BETWEEN val1 AND val2.
You need to store the dates as either DATE field types or DATETIME field types. Migrate your database with a script (shouldn't be too hard on a small DB: Backup your table, convert all of your dates to the proper format, change the schema and then re-insert your data. Restore your backup if it explodes.) After fixing this, everything will work as expected.
I would strongly recommend that you fix this by converting the fields to proper DATE fields now and take the pain, rather than waiting until the inevitable performance problems that this approach will incur arise. If you cannot, try this:
$fromday = $_POST['fromday'];
$frommonth = $_POST['frommonth'];
$fromyear = $_POST['fromyear'];
$tillday = $_POST['tillday'];
$tillmonth = $_POST['tillmonth'];
$tillyear = $_POST['tillyear'];
$sel = "SELECT * FROM bestelling WHERE SUBSTRING(verzenddatum, 7, 4) BETWEEN '$fromyear' AND '$tillyear' AND SUBSTRING(verzenddatum, 4, 2) BETWEEN '$frommonth' AND '$tillmonth' AND SUBSTRING(verzenddatum, 1, 2) BETWEEN '$fromday' AND '$tillday';"
(The hope here is that if a record's date lies outside the "from year" and "to year", the MySQL query optimiser will notice this and bail out early)
MySQL's standard date format is 'year-month-day' try this $vanaf = "$fromyear-$frommonth-$fromday"; and do the same for $tot. Try that and see if it works.
Some theory:
$startdate = sprinf('%04d-%02d-%02d', $year, $month, $day);
$enddate = sprinf('%04d-%02d-%02d', $year, $month, $day);
$query = "SELECT * FROM orders WHERE date BETWEEN '{$startdate}' AND '{$enddate}'";
My tipp: Invest some time in PDO and prepared statements. Dont use mysql_ functions anymore.
Since you are using PHP, you can set your data type in MySQL to INT (Integer) and use UNIX Timestamps for your dates. This is a good way to search for greater than and less than values.
You can use something like:
$fromday = strtotime($_POST['fromday']);
Change Only Mysql query it's Working.
select * from Your_table_name
where STR_TO_DATE( "your_date_field" , '%d/%m/%Y' )
BETWEEN STR_TO_DATE("your_first_date", '%d/%m/%Y')
AND STR_TO_DATE("your_second_date", '%d/%m/%Y')

Categories