简体   繁体   中英

PHP-POSTGRES query date(year,month) with php variables

I have the Table "appointment" you see below.

APPOINTMENT
id | app_date (date) | app_price (integer)
1 | 2013-08-21 | 45
2 | 2012-07-01 | 30
3 | 2013-08-11 | 50
.. ...... ....

I created two drop down options, one for years (eg2011,2012,2013,...) and one for months(January, February...). If the user choose "January", the query value is "01", February is "02" .... and December is "12". I want the user to "Submit" after he chooses year and month and then to receive results for the appointments.

I wrote the code you see bellow.

$year=$_GET['year']; //e.g. 2013
$month=$_GET['month']; //e.g. 08
if ($_GET['stat']==true) {
$con = pg_connect("host=localhost dbname=appdb user=postgres password=111")
or die('Could not connect: ' . pg_last_error());  
$query="select app_date, app_price
from appointment
where TO_CHAR(app_date, 'YYYY')='$year' AND TO_CHAR(app_date, 'MM')='$month' ";
$result=pg_query($query);
echo "<table align='center' width='20%' border='1'>
<th>".$month."</th>";
while ($row=pg_fetch_array($result))
 {   
$sum=$sum+$row['app_price'];
$sum_app=$sum_app+1;
}
echo "<tr><td>TOTAL APPOINTMENTS:</td><td>".$sum_app."</td><tr>
<tr><td>TOTAL PRICE:</td><td>".$sum."</td><tr>";
}
?>

After I submit it I get no results. I think that the variables $year='2013' and $month='08' are not the right type of values to equalize with the "date" datatype. How should I equalize it?

Thank you all in advance.

If you have index on field app_date , it will be ignored, and whole table will be scanned. Better example would be to use comparison operator, like BETWEEN :

$dt = new DateTime("$year-$month-1");
$sql = "
    SELECT app_date, app_price
    FROM appointment
    WHERE app_date BETWEEN '{$dt->format('Y-m-d')}' AND '{$dt->format('Y-m-t')}'
";

Demonstration .

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