我正在尝试在 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;
}
我有一个表单,用户可以在其中输入一个数字,但是当我点击计算时,它不会显示任何结果。
最佳答案
你在它结束之前关闭你的开关,https://eval.in/418432。错误报告会显示这一点。除此之外,您正在运行相同的代码两次。不妨使用查询中的值(注意我们将值转换为 int
,永远不要将用户输入直接传递给查询,这会打开 SQL 注入(inject),此驱动程序的另一种方法是 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.
}
最好将您的数据库驱动程序更新为 mysqli
或 pdo
,这将允许您使用准备好的语句。
这里有一个关于获取错误消息的线程,
How to get useful error messages in PHP?
还有一个关于 SQL 注入(inject)预防的线程,
关于php - 我正在尝试根据用户选择值执行计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32081092/