(Php)使用MONTH NAME和YEAR创建具有多个选项的搜索查询

时间:2012-07-25 11:29:17

标签: php mysql database search

所以我有一个表格有3个不同标准的下拉列表,一个是搜索月份(mes),年份(ano)和类型(tipo_id)。

我想做什么,并且由于这里的许多问题我能够前进到这个地方,当你从3个下拉菜单中选择一些东西,2或1时,它会显示一个表格,提供有关它的信息,我可以做到,但只是针对tipo_id,我认为问题在于使用MONTHNAME和YEAR在我的代码中使用的方式,我想知道如何才能使这项工作,提前感谢

 // Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

$mes = mysql_real_escape_string($_POST['mes']);
$ano = mysql_real_escape_string($_POST['ano']);
$tipo = mysql_real_escape_string($_POST['tipo_id']);


$meses = array( 
  Janeiro => 'January', 
  Fevereiro =>'February', 
  Março =>'March', 
  Abril =>'April', 
  Maio =>'May', 
  Junho =>'June', 
  Julho => 'July', 
  Agosto =>'August', 
  Setembro =>'September', 
  Outubro =>'October', 
  Novembro =>'November', 
  Dezembro =>'December' 
); 


$sql4 = "SELECT * FROM fluxo ";
$searches = array();
if ($mes  != '') $searches[] = " OR MONTHNAME(data) = '".$meses[$mes]."'";
if ($ano  != '') $searches[] = " OR YEAR(data) = '".$ano."'";
if ($tipo != '') $searches[] = " OR tipo = '".$tipo."'";
if (count($searches) > 0) {
   $sql4 .= " WHERE 1 " . implode(" AND ", $searches);

echo "sql4=$sql4\n";



//$sql4 = "SELECT tipo, movimento, valor, data FROM fluxo WHERE tipo = '".$tipo."' AND MONTHNAME(data) = '".$meses[$mes]."' AND YEAR(data) = '".$ano."' ";
//$result4=mysql_query($sql4); 

$result5 = mysql_query('SELECT SUM(valor) AS value_sum FROM fluxo GROUP BY tipo having count(tipo)>1'); 
$row5 = mysql_fetch_assoc($result5); 
$sum5 = $row5['value_sum'];

$n=1; 

echo "<p>Os seus resultados:<p>";

echo "<table border=0>";
echo "<tr bgcolor='#CCFFCC'>";
echo "<td style='width: 100px;'>Tipo</td>";
echo "<td style='width: 100px;'>Movimento</td>";
echo "<td style='width: 100px;'>Valor</td>";
echo "<td style='width: 100px;'>Data</td>";
echo "</tr>";

while($row = mysql_fetch_array($result4)){ 
    echo "<tr bgcolor='#CCCCCC'>";
    echo "<td style='width: 100px;'>".$row['tipo']."</td>";
    echo "<td style='width: 100px;'>".$row['movimento']."</td>";
    echo "<td style='width: 100px;'>".$row['valor']."</td>";
    echo "<td style='width: 100px;'>".$row['data']."</td>";
    echo "</tr>";

}

echo "</table>";

2 个答案:

答案 0 :(得分:0)

这应该有效:

$sql4 = "SELECT * FROM fluxo ";
$searches = array();
if ($mes  != '') $searches[] = " MONTHNAME(data) = '".$meses[$mes]."'";
if ($ano  != '') $searches[] = " YEAR(data) = '".$ano."'";
if ($tipo != '') $searches[] = " tipo = '".$tipo."'";
if (count($searches) > 0) {
   $sql4 .= " WHERE 1 " . implode(" AND ", $searches);
}

答案 1 :(得分:0)

在内爆$searches后,您最终会遇到一个查询,其中包含最多3个WHERE个关键字。删除前两个WHERE应该可以解决问题。