阻止用户在我的添加到购物车中输入数字0

时间:2018-04-03 05:30:41

标签: php

在我的查询中添加什么以防止用户从输入中添加数字0,因为如果输入0则接受它并仍然通过购物车

这是我的代码

<?php
include('session.php');
if(isset($_POST['cart'])){
    $id=$_POST['id'];
    $qty=$_POST['qty'];

    $query=mysqli_query($conn,"select product_qty from product where productid='$id'");
$result=mysqli_fetch_object($query);
if($result->product_qty < $qty){
   echo 'Input must be lower than the stocks';
} else{
        $query=mysqli_query($conn,"select * from cart where productid='$id' and userid='".$_SESSION['id']."'");
        if (mysqli_num_rows($query)>0){
            echo "Product already on your cart!";
        }
        else{
            mysqli_query($conn,"insert into cart (userid, productid, qty) values ('".$_SESSION['id']."', '$id', '$qty')");
        }
  }
}

Picture of the system with the error 非常感谢。

2 个答案:

答案 0 :(得分:1)

    include('session.php');
if(isset($_POST['cart'])){
    $id=$_POST['id'];
    $qty=$_POST['qty'];
if($qty>0){//This Condition work for you
    $query=mysqli_query($conn,"select product_qty from product where productid='$id'");
$result=mysqli_fetch_object($query);
if($result->product_qty < $qty){
   echo 'Input must be lower than the stocks';
} else{
        $query=mysqli_query($conn,"select * from cart where productid='$id' and userid='".$_SESSION['id']."'");
        if (mysqli_num_rows($query)>0){
            echo "Product already on your cart!";
        }
        else{
            mysqli_query($conn,"insert into cart (userid, productid, qty) values ('".$_SESSION['id']."', '$id', '$qty')");
        }
  }
}
}

答案 1 :(得分:0)

我只想改变这个

include('session.php');
if(isset($_POST['cart']) && !empty($_POST['qty'])){
   $id=$_POST['id'];
   $qty=$_POST['qty'];
....

在PHP empty中看到0为空,所以&& !empty(0) = false哪个条件无效,并且内部没有任何内容运行。

如果您想输出错误信息,请按照这样做

 if(isset($_POST['cart'])){
   if(!empty($_POST['qty'])){
      //if we are bailing on empty no need to do any of this
      $id=$_POST['id'];
      $qty=$_POST['qty'];
      .... other stuff ....
   }else{
      //if it's not !empty then it must be empty.
      echo "Please enter a quantity";
   }
}

P.S空的好处是,这也是空的''。我要添加的唯一内容可能是trim()会阻止' ',但如果您只允许#那么大部分都应该没问题。

一位聪明人曾经告诉过我很多个月,用Please开始每个表单验证错误,这样你就不会设置一个指责最终用户的语气。我以为他已经满满的,但无论如何我还是这样做了......哈哈

我看到了你的评论

  

有没有办法回应0是无效数字

当然但是这意味着什么,如果我填写这个并且它说的话。这对我意味着什么?如果它说&#34;请输入数量&#34;那很清楚。