根据表单输入过滤数据库查询

时间:2011-08-30 12:11:06

标签: php mysql

您好我无法让我的脚本完全正常运行。

我有正确计算但现在需要查询燃料类型。

<?php

include 'mysql_connect.php';

$query = "SELECT * FROM fuel_price WHERE FuelType='Oil'" ;

$result = mysql_query($query);
$price= mysql_fetch_array($result);


if(isset($_POST['submit'])){

 echo "The Price Today is  ";

 echo "£"; echo $_POST['qtylitres'] * $price ['Price'];



 } else {

echo "Please select value";

}

?>

我需要检查表格中选择的燃料类型并相应地计算总额。

例如$ query =“SELECT * FROM fuel_price WHERE FuelType ='{$ _ POST ['fueltype'];}'”;

请帮助任何有压力的人。

由于

2 个答案:

答案 0 :(得分:1)

include 'mysql_connect.php';

if(isset($_POST['submit'])){
    if($_POST['inputEmail'] == ''){
        echo 'Please enter an email address';
    } else{
        // show price
        $fuelPriceQuery = sprintf("SELECT `Price` FROM fuel_price WHERE FuelType = '%s' LIMIT 1",
                    mysql_real_escape_string($_POST['fueltype']));

        $fuelPriceResult = mysql_query($fuelPriceQuery);
        $price           = mysql_fetch_array($fuelPriceResult, MYSQLI_ASSOC);
        echo 'The Price Today is £'.($_POST['qtylitres'] * $price['Price']);

        // insert email
        $addEmailQuery  = sprintf("INSERT INTO `subscribe`(`Email`) VALUES('%s')",
                            mysql_real_escape_string($_POST['inputEmail']));
        $addEmailResult = mysql_query($addEmailQuery);
        if($addEmailResult){
            echo 'You have successfully subscribed';
        } else{
            echo 'Sorry, we could not subscribe you at this time. Please try again.';
        }
    }
} else {
    echo "Please select value";
}

有几点需要注意:

  1. 总是确保使用mysql_real_escape_string转义用户输入,如果您没有使用PDO,MySQLi等预处理语句......

  2. 我在查询中添加了LIMIT子句,因此mysql_fetch_array将起作用,因为如果它返回多行,则必须在循环中处理它。

  3. 没有必要使用多个echo,事实上如果使用尽可能少的话会更好。

答案 1 :(得分:1)

$fueltype = mysql_real_escape_string($_POST['fueltype']);
$query = "SELECT price 
          FROM fuel_price 
          WHERE FuelType= '$fueltype'
          ORDER BY pricedate DESC
          LIMIT 1 ";

解释

  1. 始终使用PDO或mysql_real_escape_string()
  2. 不要SELECT *,只选择您需要的字段。
  3. 将注入的$var放在单引号中,否则mysql_real_escape_string()将无效!
  4. 如果您只需要一个价格,请仅选择1.使用limit 1仅获取1,order by ... DESC获取最新信息。