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'
Related
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...
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
Would be grateful for some help!
Database Tables are set up like this:
id(varchar),
temp(varchar),
humi(varchar),
time(varchar)
Then I thought the user to input the ID, start date and end date.
The problem is how the string in the Time column is formatted, example: 18/03/14: 21:52:36
The user should not have to enter the time, just the date.
I thought it would be possible to do in a similar way:
$result = mysql_query("SELECT * FROM $tbl WHERE id = '$id' AND time BETWEEN '$start%' AND '$stop%'");
But it did not work.
Is it possible to do this with a sql query when the date is stored in such a way?
Regards
. Anders
Edit:
It did not work, probably because I'm doing wrong though = /
If I do this:
$start= "13/02/14 : 12:17:34";
$stop = "13/02/14 : 12:36:18";
$result = mysql_query("SELECT * FROM $tbl WHERE id = '$id' AND tid BETWEEN '$start' AND '$stop'");
..the data will appear as expected
But when I try to to use str_to_date () ,it did not work as I thought, or it did not come out any data at all.
$start= "13/02/14";
$stop = "10/02/14";
$id = "3E000004C6DB8D28";
$result = mysql_query("SELECT * FROM $tbl WHERE id = '$id' AND tid BETWEEN str_to_date('$start%', '%d/%m/%Y') AND str_to_date('$stop%', '%d/%m/%Y')");
edit2:
Do not really know what I was doing weird the first time, but now it works with this code:
$result = mysql_query("SELECT * FROM $tbl WHERE id = '$id' AND tid BETWEEN '$start' AND '$stop'");
You need to use str_to_date():
WHERE id = '$id' AND
tid BETWEEN str_to_date('$start%', '%d/%m/%Y') AND str_to_date('$stop%', '%d/%m/%Y')
Obviously, you can also do this in the application before inserting the values into the query. If so, convert the values to 'YYYY-MM-DD' format.
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.
I have a mysql database of entries
with dates. So what I want is to show
all the dates in my database and then
under each date, I want to show all
the entries in the database entered on
the specefic date. I am thinking of
two loops but I don't know how to
write the condition to display all the
dates in my database before I loop out
the entries under that date.
<?php
$sql = 'select start_date, name from events order by start_date';
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
while ($row = mysql_fetch_assoc($res)) { if ($row['start_date'] != $prev_date) {
echo "<h1>{$row['start_date']}</h1>"\n;
$prev_date = $row['start_Date']; }
echo "<p>{$row['name']}</p>"; }
?>
In a previous question (Looping out mysql data), I resulted in using this code. It pulls the date and time from MYSQL, and I used NOW() to store both date and time. How can I make it ignore the time so I can achieve what I want?
as David Andres mentions in the comment, DATE() extracts the date part of a date or datetime expression. so you can do the following:
<?php
$sql = 'SELECT DATE(start_date) AS start_date_date, name FROM events ORDER BY start_date';
$res = mysql_query($sql) or die(mysql_error());
$prev_date = null;
while ($row = mysql_fetch_assoc($res)) {
if ($row['start_date_date'] != $prev_date) {
echo "<h1>$row[start_date_date]</h1>\n";
$prev_date = $row['start_date_date'];
}
echo "<p>$row[name]</p>";
}
Use CURDATE() instead of NOW().
Try it with a condition like this:
SELECT * FROM `events` WHERE DATE(`start_date`) = '2009-09-09';
This'll get you all events from the database for Sep 9th 2009. I think that's what you're asking for, is it?
Untested code that I will probably need someone to correct, but here goes:
SQL to retrieve all the dates that exist in the table:
$sql_get_dates = 'select start_date from events order by start_date distinct';
And, assuming start_date is a DATETIME type, the SQL to get all events on a given date:
$sql_get_events = 'select * from events where date(start_date) = "2009-08-09"';
Instead of just selecting the date, you could use some of the MySQL time functions to truncate the date.
$sql = "select date_format(start_date, '%Y-%m-%d') as fstart_date, name from events order by start_date";
Of course, you'll have to change start_date to fstart_date within the PHP code.
Check out the Mysql reference page for DATE_FORMAT().