从文本框到数据库进行比较

时间:2014-02-20 12:40:56

标签: php

请帮帮我。我在比较方面遇到了麻烦 如何比较从数据库中的库存中插入的数量

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

//empty cart by distroying current session
if(isset($_GET["emptycart"]) && $_GET["emptycart"]==1)
{
    $return_url = base64_decode($_GET["return_url"]); //return url
    session_destroy();
    header('Location:'.$return_url);
}

//add item in shopping cart
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
    $product_code   = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); //product code
    $product_qty    = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //product code
    $return_url     = base64_decode($_POST["return_url"]); //return url
    $sel = mysql_query("SELECT * FROM products");
    $product_stock = mysql_fetch_assoc($sel);
    //limit quantity for single product
    if($product_qty > $products['stock'])
    {
        die('<div align="center">Not enought quantity<br /><a href="index.php">Back To Products</a>.</div>');
    }

2 个答案:

答案 0 :(得分:0)

您的错误就在这一行:

if($product_qty > $products['stock'])

什么是$products['stock']?上面你定义了MySQL结果:

$product_stock = mysql_fetch_assoc($sel);

所以,你的意思是?

if($product_qty > $product_stock['stock'])

此外,您的代码容易受到重定向攻击:https://www.owasp.org/index.php/Top_10_2013-A10-Unvalidated_Redirects_and_Forwards

您需要确保以某种方式验证参数return_url,只允许有效的URL列表。更好的是:

$valid_urls = array(1 => 'http://link1.com', 2 => '...');

然后:

$return_url_param = (int)$_GET["return_url"];
$return_url = isset($valid_urls[$return_url_param] ? $valid_urls[$return_url_param] : 'http://defaulturl.com');

答案 1 :(得分:0)

您正在从错误的变量中比较$product_qty。尝试将$products['stock']更改为$product_stock['stock']

更正后的代码块: -

<?php

//add item in shopping cart
if (isset($_POST["type"]) && $_POST["type"] == 'add') {
    $product_code = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); //product code
    $product_qty = filter_var($_POST["product_qty"], FILTER_SANITIZE_NUMBER_INT); //product code
    $return_url = base64_decode($_POST["return_url"]); //return url
    $sel = mysql_query("SELECT * FROM products");
    $product_stock = mysql_fetch_assoc($sel);
    //limit quantity for single product
    if ($product_qty > $product_stock['stock']) {
        die('<div align="center">Not enought quantity<br /><a href="index.php">Back To Products</a>.</div>');
    }
}