My question is similar to [this][1] but the solution provided there doesn't work for me.
I have a DB and I have one column called birth that contains a date in the format year-day-month 00:00:00. Now I want to extract from the DB all the records which birth is between two dates.
The birth value has been inserted in the DB with this code
$date = $day . "-" . $month. "-" . $year;
$a = strptime($date, '%d-%m-%Y');
$DB_date = date('Y-m-d H:i:s',mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900));
To extract the dates I am using this code:
$stmt = $conn->prepare('SELECT * FROM database WHERE `birth` BETWEEN ? AND ?');
$start_date = '1990-01-01';
$stop_date = '1995-01-01';
$stmt->bind_param('ss',$start_date,$stop_date);
$stmt->execute();
$result = $stmt->get_result();
but it doesn't find anything so $result->num_rows is equal to 0 and it doesn't give any errors so the problem must be in the comparison of the dates.
Birth column format is y-d-m hour min sec. But in your where clause you are ignoring hour minute second factor.
Replace:
$start_date = '1990-01-01';
$stop_date = '1995-01-01';
With this:
$start_date = '1990-01-01 00:00:00';
$stop_date = '1995-01-01 00:00:00';
Kindly try it and let me know if it works
I found the solution
The code in my question works if the data type of the column in the DB is datetime and you also need to make sure that $start_date is older than $stop_date. I still wonder though why it didn't work with the date data type.
I had the same issue. I found another thread with the same problem (not sure how to duplicate this thread) here
However just to sum up,
They managed to get the desired results by bracketing the question marks for the params.
$stmt = $conn->prepare('SELECT * FROM database WHERE `birth` BETWEEN (?) AND (?)');
$start_date = '1990-01-01';
$stop_date = '1995-01-01';
$stmt->bind_param('ss',$start_date,$stop_date);
$stmt->execute();
$result = $stmt->get_result();
Hope this helps.
Related
I am trying to get data on a database between two timestamps and I have seen many posts that use the BETWEEN. But I can't get past the error that is related to my bindparams that's why I can't test the codes that I saw on another post.
About the first part of my code, I just thought that the value on $date1 and $date2 is a string and I thought that maybe I need it to be converted to a MySQL timestamp format so I used the following code.
How do I use bindparams on a timestamp based on my code?
I tried the following code but I keep getting an error on POSTMAN.
such as Number of variables doesn't match the number of parameters
This is the sample value for date1 and date 2 that I am using on Postman for testing
$date1 is 2019-12-13 00:00:00
$date2 is 2019-12-15 00:00:00
DbOperation.php
//view cart product sales in cartData via date
public function viewCartDatabyDate($date1, $date2){
$timestamp1 = strtotime($date1);
$timestamp2 = strtotime($date2);
$newDate1=date("Y-m-d H:i:s", $timestamp1);
$newDate2=date("Y-m-d H:i:s", $timestamp2);
$stmt = $this->con->prepare("SELECT * FROM cart_data WHERE created BETWEEN '$newDate1' AND '$newDate2' ORDER BY created");
//$stmt->bind_param("s", $newDate1);
//$stmt->bind_param("s", $newDate2);
$stmt->bind_param("s", $created);
$result = $stmt->get_result();
while($data = $result->fetch_assoc()){
$cartdata[]=$data;
}
return $cartdata;
}
You need to use placeholders. Question marks in SQL mean that this is the place where the variable is attached.
$stmt = $this->con->prepare("SELECT * FROM cart_data WHERE created BETWEEN ? AND ? ORDER BY created");
$stmt->bind_param("ss", $newDate1, $newDate2);
$result = $stmt->get_result();
$certdata = $result->fetch_all(MYSQLI_ASSOC);
So I am working on a simple website and I ran into a problem. I have a subscription based website and I have a date expired for when their subscription ends. This all works well, but when I tried to display the expiration date I ran into problems. The first 3 lines are what i have been trying. It seems as if the timestamp isnt correctly being transferred from the database because when I did my test at the button, this displayed the correct date. The top 3 lines always give me this: 1970/01/01
// Get Expiration Date
// Always gives me 1970/01/01
$datexpire = "SELECT date-expire FROM users WHERE username='{$_SESSION['username']}'";
$timestamp = mysqli_query($link, $datexpire);
$date = date("Y/m/d",$timestamp);
//This works
$timestamp2 = 1537847863;
$date2 = date("Y/m/d",$timestamp2);
If anyone could help that would be much appreciated
i think your code should be something like
$datexpire = "SELECT date-expire FROM users WHERE username='{$_SESSION['username']}'";
$result = mysqli_query($link, $datexpire);
$row=mysqli_fetch_assoc($result));
$timestamp = $row['date_expire'];
$date = date("Y/m/d", $timestamp);
echo $date;
please check for column name.. if it is date-expire or date_expire ??? (dash or underscore ??)
mysqli_query returns a mysqli_result object or a boolean value.
You want to fetch a row from your given object, like so:
$datexpire = "SELECT `date-expire` FROM users WHERE username='{$_SESSION['username']}'";
$result = mysqli_query($link, $datexpire);
$row = mysqli_fetch_assoc($result);
$date = date("Y/m/d", $row["date-expire"]);
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
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')
All I'm trying to do is make the php file accumulate the end date from the sub date. I don't understand why this strtotime function isn't working. My database stores dates as "Y-m-d".
here's the code:
//disguised for security reasons
$db = mysql_connect("*******", "*******","********");
mysql_select_db("*******",$db);
$getad = mysql_query("SELECT id, annual_sub_date FROM members WHERE annual_sub_date!=null", $db);
while ($gad = mysql_fetch_array($getad)) {
$id = $gad['id'];
$asd = $gad['annual_sub_date'];
$aedate_time = strtotime('+1 year', $asd);
$aedate = date("Y-m-d", $aedate_time);
mysql_query("UPDATE members SET annual_end_date='$aedate', annual_active='Y' WHERE id='$id'");
}
---------SOLVED IT---------
I went and played XBox Split/Second for a bit and then realised the issue. My mind went back to PHP/MySQL 101. I coded everything right except the "!=null" part.
//Wrong Way
$getad = mysql_query("SELECT id, annual_sub_date FROM members WHERE annual_sub_date!=null", $db);
//Correct Way
$getad = mysql_query("SELECT id, annual_sub_date FROM members WHERE annual_sub_date IS NOT NULL", $db);
Now everything works :) That's the issues you can expect coding at 5:01am.
The first argument to strtotime is an absolute or relative date as a string, the second argument is an integer timestamp. You're giving it a relative date (string) as the first argument and an absolute date (also string) as the second. You need to convert $asd to a timestamp using strtotime first.
$aedate_time = strtotime('+1 year', strtotime($asd));
BTW, you could do the whole date calculation and updating in SQL with a single query, no need to take the long way around through PHP.
It's because strtotime requires timestamp as second argument and not string date in Y-m-d.
Just try code snippet below to see what I ment.
$gad = array('annual_sub_date' => '2010-11-21');
// wrong
// $asd = $gad['annual_sub_date'];
// good; convert to timestamp
list($year, $month, $day) = explode('-', $gad['annual_sub_date']);
$asd = mktime(0, 0, 0, $month, $day, $year);
$aedate_time = strtotime('+1 year', $asd);
$aedate = date("Y-m-d", $aedate_time);
echo $aedate . "\n";