我尝试根据用户选择值执行计算

时间:2015-08-18 19:29:28

标签: php mysql

我试图在php中创建一个查询,从数据库中检索值并将它们与用户输入相乘。用户选择一个项目输入一个数字,我希望查询将数字乘以不同的值,具体取决于用户选择的项目。例如,当用户从id 1中选择一个项目并输入一个数字时,我希望查询从id 1中检索值与数字相乘,如果用户选择id 2,则该数字应该与id 2中的值相乘这是我到目前为止所拥有的。

$value = isset($_POST['selection']);
switch ($value){
case 1 :
$strSQL = "SELECT * FROM table1 WHERE id ='1' ";
$rs = mysql_query($strSQL);
while ($row = mysql_fetch_array($rs)) {
    $q1 = $row['Rate_1' ];
    $q2 = $row['Rate_2'];
}
$c1 = $input * $q1 ;                       
$c2 = $input * $q2 ;
$total = $c1 + $c2;
echo $total;
break; }
case 2 :
$strSQL = "SELECT * FROM table1 WHERE id ='2' ";
$rs = mysql_query($strSQL);
while ($row = mysql_fetch_array($rs)) {
    $q1 = $row['Rate_1' ];
    $q2 = $row['Rate_2'];
}
$c1 = $input * $q1 ;                       
$c2 = $input * $q2 ;
$total = $c1 + $c2;
echo $total;
break;
}

我有一个用户输入数字的表单,但是当我点击计算时,它不会显示任何结果。

1 个答案:

答案 0 :(得分:1)

您正在关闭交换机https://eval.in/418432。错误报告会显示这一点。除此之外,您运行相同的代码两次。不妨使用查询中的值(注意我们将值转换为int,永远不要将用户输入直接传递给查询,这会打开SQL注入,这个驱动程序的另一种方法是,http://php.net/manual/en/function.mysql-real-escape-string.php )。

    if(isset($_POST['selection']) && ($_POST['selection'] == 1 || $_POST['selection'] == 2)){
          $id = (int)$_POST['selection'];
          $strSQL = "SELECT * FROM table1 WHERE id = $id";
          $rs = mysql_query($strSQL);
          $row = mysql_fetch_array($rs); // id is auto-incrementing presumably so no need to loop, only 1 row
          $q1 = $row['Rate_1' ];
          $q2 = $row['Rate_2'];
          $c1 = $input * $q1 ; //dont know where $input is defined but presuming you took care of that else where in the code                   
          $c2 = $input * $q2 ;
          $total = $c1 + $c2;
          echo $total;
     } else {
          echo 'Invalid value passed in';// or do nothing here and take out the else.
     }

最好将您的数据库驱动程序更新为mysqlipdo,这样您就可以使用预准备语句。

这是获取错误消息的主题,

How to get useful error messages in PHP?

和一个关于SQL注入预防的线程,

How can I prevent SQL injection in PHP?