简体   繁体   中英

Select records between two dates

I have a php file which will get inputs from another php file and show the data in a html table, but in the sql statement I dont get the date field filtered in it, may be the date format is incorrect. Please help me with this

My Code is below

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }

 mysql_select_db("marketnews", $con);




$date1 = explode('/', $_POST['ADate']);
$time = mktime(0,0,0,$date1[0],$date1[1],$date1[2]);
$mysqldate = date( 'Y-m-d H:i:s', $time );


$date2 = explode('/', $_POST['BDate']);
$time = mktime(0,0,0,$date2[0],$date2[1],$date2[2]);
$mysqldate1 = date( 'Y-m-d H:i:s', $time );

$sec= "$_POST[id]";


echo "<br>";
echo "$mysqldate1";
echo "<br>";
echo "$sec";*/


$result = mysql_query("SELECT * FROM mktnews where security = '$sec' and eventdate    between '$mysqldate' and '$mysqldate1'");
echo '<a href="main.html"><b>BACK</b></a>';
echo "<br>";
echo "<table border='2' BORDERCOLOR=GREEN align='center' >
<tr>
<th>Firm</th>
<th>Name</th>
<th>NIC</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['eventdate'] . "</td>";
  echo "<td>" . $row['news'] . "</td>";
  echo "<td>" . $row['security'] . "</td>";
   echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?> 

date format of this MySql table is like this

2013-04-11

Please help me with this

Your date format looks correct depending on the structure of your table, however you're missing quotations in your mysql statement.

should look like this:

 $result = mysql_query("SELECT * FROM mktnews where security = '".$sec."' and eventdate    between '".$mysqldate."' and '".$mysqldate1."'");

as I'm sure you know, you should escape your queries too.

you must have to change date format to compare as date format in your mysql table

use

$mysqldate = date( 'Y-m-d', $time ); instead of $mysqldate = date( 'Y-m-d H:i:s', $time );

and

$mysqldate1 = date( 'Y-m-d', $time ); instead of $mysqldate1 = date( 'Y-m-d H:i:s', $time );

will return result as you want.

change

$mysqldate = date( 'Y-m-d H:i:s', $time );

to

 $mysqldate = date( 'Y-m-d', $time );

and same for $mtsqldate1

your php time format and mysql time format are different

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM