PHP将数据库中的int与POST [int]进行比较

时间:2013-06-16 16:42:27

标签: php mysql post compare int

我遇到以下代码问题:

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

$name = $_POST['productname'];
$sql= "SELECT quantity FROM products WHERE productid='$name'";
$amount= $sql + 0;
$quantitysold = $_POST['quantitysold']; 
$amountsold = $quantitysold + 0;
var_dump($amountsold);
var_dump($amount);

if($amountsold > $amount){
    echo 'Not enough product';}

else if($name && $quantitysold){
    $query = $db->query("UPDATE products SET quantity=quantity-$quantitysold
    WHERE productid='$name'");
    $query = $db->query("DELETE FROM products WHERE quantity<'1'");} 

else{
    echo 'Incomplete Data';}

}

问题是sql被读取为字符串,而不是我希望将其重定向到的整数。这意味着我无法比较$ amount和$ quantitysold。

我最近开始学习PHP,所以这可能是一个菜鸟错误。

2 个答案:

答案 0 :(得分:2)

使用来自php函数的过滤器输入

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

$name = filter_input(INPUT_POST, "productname",FILTER_SANITIZE_NUMBER_INT);
$sql= "SELECT quantity FROM products WHERE productid=$name";
$amount= $sql + 0;
$quantitysold = $_POST['quantitysold']; 
$amountsold = $quantitysold + 0;
var_dump($amountsold);
var_dump($amount);

if($amountsold > $amount){
    echo 'Not enough product';}

else if($name && $quantitysold){
    $query = $db->query("UPDATE products SET quantity=quantity-$quantitysold
    WHERE productid=$name");
    $query = $db->query("DELETE FROM products WHERE quantity<'1'");} 

else{
    echo 'Incomplete Data';}

}

答案 1 :(得分:0)

代码的第一部分没有将sql查询字符串传递给sql引擎。以下是使用PDO(Php Data Objects

时的方法
if(isset($_POST['submit'])){

    $db = new PDO("mysql:host=localhost;dbname=yourdatabasename","yourusername","yourpassword");
    $name = $_POST['productname'];
    $sql= "SELECT quantity FROM products WHERE productid=?";
    $statement = $db->prepare($sql);
    $statement->execute(array($name));
    $row = $statement->fetch(PDO::FETCH_NUM);
    $amount= $row[0];

// the rest of your code