简体   繁体   English

使用PHP变量的PHP-POSTGRES查询日期(年,月)

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

I have the Table "appointment" you see below. 我在下面看到表格“约会”。

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

I created two drop down options, one for years (eg2011,2012,2013,...) and one for months(January, February...). 我创建了两个下拉选项,一个选项用于多年(例如2011、2012、2013等),另一个选项用于几个月(一月,二月...)。 If the user choose "January", the query value is "01", February is "02" .... and December is "12". 如果用户选择“一月”,则查询值为“ 01”,二月为“ 02” .....,十二月为“ 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. 我认为变量$ year ='2013'和$ month = '08'不是与“ date”数据类型相等的正确值类型。 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. 如果您在字段app_date上有索引,它将被忽略,并将扫描整个表。 Better example would be to use comparison operator, like BETWEEN : 更好的例子是使用比较运算符,例如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 . 示范

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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