MYSQL / PHP输入变量不产生所需的结果

时间:2017-08-01 13:42:41

标签: php mysql

我正在尝试使用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);

2 个答案:

答案 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)

<强>更改

  1. 使用反引号而不是单引号附上列名。
  2. 根据条件更改body { margin: 25mm 25mm 25mm 25mm; } 值。
  3. <强> 编辑-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"));