我正在尝试使用PHP对mysql数据库进行简单的选择查询,其中根据用户输入设置了两个变量。一个变量是一个月,因此一次只能是一个特定值。另一个是动态的,可以是特定值,也可以是表中的所有值。代码看起来类似于:
$var1 = "-1";
if (isset($_GET['Month'])) {
$var1 = $_GET['Month'];
}
$var2 = $_GET['Person'];
if ($var2 == "All") {
$var2 ="('Person 1' or 'Person 2' or 'Person 3')";
}
$query= sprintf("Select * from Table where `Month` = %s and `Person` = %s", GetSQLValueString($var1, "text"), GetSQLValueString($var2, "text"));
当我为$ var2输入特定的人时,我能够得到正确的结果,但是,当我为$ var2输入All时,代码会运行,但我没有返回结果。
实际代码块:
$colname_chainsales = "-1";
if (isset($_GET['Period'])) {
$colname_chainsales = $_GET['Period'];
}
$rep = $_GET['Rep'];
if ($rep == "All") {
$rep = " 1=1 ";
} else {
$rep = " `PSIP` = ".$_GET['Rep'];
}
mysql_select_db($database_PPSC, $PPSC);
$query_chainsales= sprintf("select `PSIP` as `Sales Rep`, `Month`, `chainsales`.`PPSC #` as `PPSC #`, `chainsales`.`Store Name` as `Store Name`, sum(`Sales Less Credits ($)`) as `Sales Less Credits ($)`, sum(`RX Sales`) as `RX Sales`, sum(`Brand RX`) as `Brand RX`,sum(`Brand Rx C2`) as `Brand Rx C2`,sum(`prnr sales`) as `prnr`,sum(`h2h sales`) as `h2h`,sum(`specialty sales`) as `Specialty`,sum(`Brand RX`)-sum(`Brand Rx C2`)- sum(`specialty sales`)-sum(`h2h sales`) as `Net Brand`, sum(`Pro w/SG`) as `Pro w/SG` , sum(`Pro w/o SG`) as `rpro`, SUM(`Pro w/SG`) / (SUM(`RX Sales`)- SUM(`specialty sales`))* 100 AS `Compliance` from `chainsales` inner join `clients` on `chainsales`.`ppsc #`=`clients`.`ppsc #` WHERE `Month` = %s and %s Group by `PPSC #`, `Month` ORDER BY `PSIP`", GetSQLValueString($colname_chainsales, "text"), GetSQLValueString($rep, "text"));
$chainsales = mysql_query($query_chainsales, $PPSC) or die(mysql_error());
$row_chainsales= mysql_fetch_assoc($chainsales);
$totalRows_chainsales = mysql_num_rows($chainsales);
答案 0 :(得分:0)
在查询中使用in
运算符代替=
,如下所示:
Select * from Table where 'Month' = %s and 'Person' in %s", GetSQLValueString($var1, "text"), GetSQLValueString($var2, "text")
此外,当您将$var2
定义为人员列表时,请将“或”更改为逗号:
if ($var2 == "All") {
$var2 ="('Person 1', 'Person 2' , 'Person 3')";
} else {
$var2 ="('".$_Get['Person']."')" ;
}
答案 1 :(得分:0)
<强>更改强>
body {
margin: 25mm 25mm 25mm 25mm;
}
值。<强> 编辑-1 强>
假设,
案例1: $var2
::查询将附加到$var2 = "All"
运营商。
案例-2: IN
::查询将附加到$var2 = 1
运营商。
更新代码
=
<强> 编辑-2 强>
参考OP评论:当我为$ var2输入All时,我应该得到一个结果显示表格中的所有内容,
$var1 = "-1";
if (isset($_GET['Month'])) {
$var1 = $_GET['Month'];
}
$var2 = $_GET['Person'];
if ($var2 == "All") {
$var2 = " IN ('Person 1', 'Person 2', 'Person 3')";
} else {
$var2 = " = ".$_GET['Person'];
}
$query= sprintf("SELECT * FROM `Table` WHERE `Month` = %s and `Person` %s", GetSQLValueString($var1, "text"), GetSQLValueString($var2, "text"));