Pulling records between two dates from a VIEW - php

I have a mysql datetime field that stores dates in the form '2013-12-25 00:00:00'
I need to select all records for any month in the table with a query like:
$sql = "SELECT *
FROM `images`
WHERE (photodate BETWEEN '2003-11-01 00:00:00' AND '2003-12-03 00:00:00')
ORDER BY photodate DESC
LIMIT 30";
The above select query does the job fine.
In order to change the dates, I need to replace the '2003-11-01 00:00:00'AND'2003-12-03 00:00:00' with variables, so I set a variable with input data from two drop down lists for $startyear and $startmonth and convert it to what I think is the correct form using:
$startdate = $startyear."-".$startmonth."-01 00:00:00";
I do the same to the $enddate by adding 1 to the $startmonth.
My code then becomes:
$sql = "SELECT *
FROM `images`
WHERE (photodate BETWEEN $startdate AND $enddate)
ORDER BY photodate DESC
LIMIT 30";
This does not work at all and gives a MySQL error. Having struggled with it for a month and finding nothing on any forum that uses variables instead of text, I am totally at a loss as to how it could be done. All help appreciated.

You are vulnerable to SQL injection attacks, which is why it's not working. You're producing the literal query
... WHERE (photodate BETWEEN 2003-11-01 00:00:00 AND 2013-12-03 00:00:00)
The 2003-11-01 and 2013-12-03 will be interpreted as a series of mathematical subtractions, and the 00:00:00 will be a simple flat-out syntax error. You need to, at bare minimum, quote those values:
... WHERE (photodate BETWEEN '$startdate' AND '$enddate')
^----------^-----^--------^--- note the quotes
so that mysql can see the WHOLE date as a date value, and not some arbitrary broken strings.

I guess you're missing some apostrophes... try this:
$sql = "SELECT * FROM images WHERE (photodate BETWEEN '$startdate' AND '$enddate') ORDER BY photodate DESC LIMIT 30";

You could have problems with the logic. In $enddate doesn't adding 1 to the start month give you 13?
Try printing out the contents $sql when the variables are in and see how it compares to the working $sql.

Please add apostrophes your query (and sanitize your variables using mysql_real_escape_string, PDO bind values, mysqli_real_escape_string) :
$sql = 'SELECT * FROM 'images' WHERE (photodate BETWEEN '.$startdate.' AND '.$enddate.') ORDER BY photodate DESC LIMIT 30';
A little reminder, you shall NOT use MySQL (deprecated, old.. and not that fast), if you're using MySQLi or going to use it, please sanitize your variables like this, as Marc B said it could break your script and your app security :
<?php
// Starting MySQLi Connection
$db = mysqli_connect("host", "user", "password", "dbname");
// Sanitizing your variables
$startdate = mysqli_real_escape_string($db, $startdate);
$enddate = mysqli_real_escape_string($db, $enddate);
// Query
$sql = "SELECT * FROM 'images' WHERE (photodate BETWEEN ".$startdate." AND ".$enddate.") ORDER BY photodate DESC LIMIT 30";
// Doing the query and print the result array
$var = mysqli_query($db, $sql);
print_r($var);
// Closing connection
mysqli_close($db);
?>
Please refer to to this for PDO way or to this for MySQLi way, you can also check the MySQL_real_escape_string into PHP doc but MySQL functions are deprecated since PHP 5.5

Related

how to select data from table according to date interval?

how to retrieve all data from table using date interval?
this is my code
<?php
include '../php_action/db_connect.php';
$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
echo 'ORDERS BETWEEN '.$startdate.' and '.$enddate;
$sql = "SELECT * from orders WHERE order_date BETWEEN '$startdate' AND '$enddate'" ;
$result=$connect->query($sql);
while($row=$result->fetch_array())
{
echo '<br>'. $row['order_id'] ;
}
?>
it isn't working, but when i change it to where order_id = 1; (for example) it works.
i even tried where order_date = 2020/03/02; still not working.
how should i work this out?
Put a semicolon after the sql statement inside the quotes.
$sql = "SELECT * from orders WHERE order_date BETWEEN '$startdate' AND '$enddate';" ;
^^
If that doesn't solve it the problem could be a number of things. You may have your MySql set to StrictDates. Depending on your setup you may have strict dates requiring additional zeros. See the following:
https://dev.mysql.com/doc/refman/8.0/en/datetime.html
When troubleshooting these I try to insert known good data and then work on identifying on how to get that data to pass through.
Try #1 - attempt this: change to specific dates and add a semi-colon to the end inside the quote:
$sql = "SELECT * from orders WHERE order_date BETWEEN '2020-01-01 10:10:10' AND '2020-03-01 10:10:10';" ;
If that works you can delete the times to identify if MySQL is in strict mode. This should help you identify where your issues are.

Comparing date() in sql query

I have 5 records in mysql database and these records have recorded date within this date interval.
$year=2015;
$month=8;
$datefrom=1;
$dateto=31;
$startdate='$year-$month-$datefrom 00:00:00';
$enddate='$year-$month-$dateto 23:59:59';
So I write a query to get these records out like this:
$sql = "SELECT id FROM newpost WHERE email=:email AND :startdate <= poststart <= :enddate AND postapproved=1";
Given that poststart column in table newpost has SQL Datetime format like this: "Y-m-d H:i:s".
But when I changed variable $year = 2016, I still got 5 results? It should return no record. Because those 5 records are recorded between 1 - 31 August 2015.
So I thought I did something wrong in the sql query especially the comparing date part but I could not configure out how to fix it?
Please help!
You can use BETWEEN in your query
$sql = "SELECT id FROM newpost WHERE email=:email AND (poststart BETWEEN :startmonth AND :endmonth) postapproved=1"
Use single quotes to wrap your date values
$sql = "SELECT id FROM newpost WHERE email=:email AND poststart BETWEEN ':startdate' AND ':enddate' AND postapproved=1";
A couple quick things to check to make sure it's not a syntactical error:
Your variable names don't match up. You defined startdate and enddate, but then in the query you used startmonth and endmonth.
You should probably also use leading zeros in your month and day, i.e.:
$month='08';
$datefrom='01';

php mysql comparing dates for equality

I am using php to access fields from 2 tables.
This part works just fine
$sql=mysql_query('SELECT * FROM user_weeks WHERE user_id = '.$_SESSION["user_id"].' ORDER BY date DESC') or die(mysql_error());
I get the date just fine by doing this
$infodate=$info["date"];
echo $infodate;
However I'm trying to take that date and compare it to one in a different table as such
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE date = '.$infodate.' ') or die(mysql_error());
however, that gives me no results. I'm a noob so sorry if this code is so "2000 and late"
Assuming both date fields are of type date, you need to wrap the name date in backticks, since date is a reserved word and you need to wrap your date in quotes.
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE `date` = "'.$infodate. '"') or die(mysql_error());
Also, mysql_* functions are deprecated. You need to look into using PDO or mysqli to query your database.
date is reserved word use to wrap inside the backtick `date
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE `date` = "'.$infodate.'" ') or die(mysql_error());
Presumably you're using a standard yyyy-mm-dd type date string in your query, which means you're lacking quotes around the date value:
$sql2=mysql_query('SELECT * FROM weekly_ROI WHERE date = '.$infodate.' ')
^--here ^-- here
Your query will look like
... WHERE date = 2013-12-18
and be evaluated as a simple mathematical subtraction:
... WHERE date = 1983
You need quotes:
.... date = "' . $infodate . '"');
^-- ^--

Sql Query Not Working with php variables

My Sql Query Returning Empty results set. Is there any Mistake in format. I am Using some php variables inside the query..
public function getBlockDate($month,$year){
$connection = db::factory('mysql');
$time_from="00-00-00";
$time_to="23-59-59";
$sql = 'select * from blocks WHERE date LIKE "'.$year.'-'.$month.'%" AND (time_From="'.$time_from.'" AND time_to="'.$time_to.'")';
return $connection->getArray($sql);
}
*Here time_from and time_to table columns are of time type*
Change your SQL query
$sql = 'select * from blocks WHERE date LIKE "'.$year.'-'.$month.'%" AND (time_From="'.$time_from.'" AND time_to="'.$time_to.'")';
' single quotes are missing over $time_from and $time_to
EDITED QUERY
$time_from="00:00:00";
$time_to="23:59:59";
$sql = 'select * from blocks WHERE date LIKE "'.$year.'-'.$month.'%" BETWEEN (time_From="'.$time_from.'" AND time_to="'.$time_to.'")';
also change the - with : in your $time_from and $time_to variables
This should work for you. You didn't put quotas right at the AND clause.
Also when using LIKE in your query be sure to place the wildcard correctly. In your case you are looking for records in date column whose start with year-month then there's your time.
$time_from="00-00-00";
$time_to="23-59-59";
$sql = "SELECT * FROM blocks WHERE date LIKE '".$year."-".$month."%' AND (time_From='".$time_from."' AND time_to='".$time_to."')";
Convert date and time to universal format and then query using it.

Getting records between 2 dates someone chooses php mysql

I'm trying to get records between 2 dates. The dates are entered in the form "yyyy-mm-dd" into a input type="text" (so for example I would type "2011-02-15" into a text input) and then posted to the next page which has the query:
$start = $_POST["start"];
$end = $_POST["end"];
$sql_query = "SELECT * FROM actionlist WHERE date>='{$start} 00:00:00' AND date<='{$end} 23:59:59' ORDER BY id";
$result = mysql_query($sql_query);
The records in the table "actionlist" have a field called "date" and this is entered automatically when creating the record by using "$date = date('Y-m-d H:i:s')".
Anyway, I can't seem to get any records to be selected. Do I need to process my $start and $end variables somehow? Thanks in advance.
You can use between to get the information you want
$sql_query = "SELECT * FROM actionlist WHERE date BETWEEN '$start' AND '$end' ORDER BY id";
But you need to make sure start and end are valid, and escaped,etc.. to prevent sql injection, and the like
$start = mysql_real_escape_string(trim($_POST["start"]));
$end = mysql_real_escape_string(trim($_POST["end"]));
$sql_query = "SELECT * FROM actionlist WHERE date BETWEEN '".$start." 00:00:00' AND '".$end." 23:59:59' ORDER BY id";
$result = mysql_query($sql_query) or die(mysql_error());
Edit: the trim() in case you have some unwanted space in your input forms; a bit of sanitation then, and use BETWEEN, as everyone has suggested right before me (damn I'm so slow at writing...)
Edit 2 based on comment below
Try that way
SELECT * FROM actionlist WHERE date BETWEEN 'start' AND 'end'

Categories