我试图在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;
}我有一个表单,用户输入一个数字,但当我单击计算时,它不会显示任何结果。
发布于 2015-08-18 19:54:02
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.
}最好将db驱动程序更新为mysqli或pdo,这将允许您使用准备好的语句。
这里有条关于获取错误信息的线索,
How to get useful error messages in PHP?
以及关于SQL注入预防的线程,
https://stackoverflow.com/questions/32081092
复制相似问题