数据库为空时禁用更新数据

时间:2015-02-13 01:33:58

标签: php mysql

当我想回应“股票低于你想要的股票”时,我遇到了问题。问题是,当我的数据库中的库存少于用户想要的库存时,用户仍然可以更新购物车。它应该显示错误“库存少于您想要的”。

这是我的代码。

<?php session_start();
require("config.php");

$user = $_SESSION['userlogin'];
$cek = mysql_query("SELECT * FROM transaksitbl WHERE username = '$user' AND status ='0'") or die(mysql_error());
$result = mysql_num_rows($cek);
$data = mysql_fetch_array($cek);
if ($result > 0)
{
$faktur =$data['notransaksi'];
for ($i=1; $i<=$_POST['n']; $i++)
{
  $idp = $_POST['id'.$i];
  $cari2 = mysql_query("SELECT * FROM barangtbl WHERE id='$idp'") or die(mysql_error());      
  $row2 = mysql_fetch_array($cari2);
  $har = $row2['harga'];
  $stock = $row2['stock'];
  if($_POST['n'] <= $row2['stock'])
  {
    echo "The stock is less than what you want";
  }
  if ($cari2)
  {
    $jmlubah = $_POST['jumlah'.$i];
    $beratnew = $jmlubah*$row2['berat'];
    $totubah = $jmlubah*$har;

    $query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah 
      WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
  }
}
}
header ("location:shopping_cart.php");
?>

1 个答案:

答案 0 :(得分:0)

如果我理解你的话

if($cari2){}

函数正在执行? 你要检查的是$ cari2变量是否为真。 只需在if($ cari2){}语句中生成一个else语句,这样如果股票小于你,那么第二个if语句就不会被执行。

所以,就像这样:

if($_POST['n'] <= $row2['stock']){
     echo "The stock is less than you want";
   }
else { 
      if($scari2){
         $jmlubah = $_POST['jumlah'.$i];
         $beratnew = $jmlubah*$row2['berat'];
         $totubah = $jmlubah*$har;

         $query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah,      jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah 
         WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or   die(mysql_error());

     } else {
        die('Woop, there seems to be a problem with the $scari2 variable. The value is:' . $scari2);
     } // END OF INNER ELSE
 } // END OF ELSE

在向变量提交数据之前,不要忘记在变量上使用 mysql_real_escape_string()函数。