donglian3055 2009-09-30 10:18
浏览 56
已采纳

比较两个数组的问题

I'm trying to compare the content of 2 arrays, basically I'm using a shopping cart and I need to check the prices of submitted forms against a database, the problem is when I have one incorrect price in the shopping cart it gives me an error message but when I have 1 correct price and 1 incorrect it continues with the checkout, I don't know what I'm doing wrong any help would be appreciated.

 foreach ($cart->get_contents() as $item)
    {
    $item_id    = $item['id'];
    $item_name  = $item['name'];
    $item_price = $item['price'];
    $item_qty   = $item['qty'];

$connection = mysql_connect($dbhost,$dbuser,$dbpass) or die("Error connecting to mysql");
mysql_select_db($dbname);

$query = "select * from products where product_name = '$item_name'";

$result = mysql_query($query);
if (!$result) {
    echo mysql_error();
}

while ($row = mysql_fetch_assoc($result)) {
    $sql_price[] = $row['product_price'];
    $qty[] = $row['product_qty'];
    $name = $row['product_name'];
}
foreach($sql_price as $price) {
    $price = $price;
    if ($price !== $item_price) {
        $valid_prices = false;
    }else{


        $valid_prices = true;
    }
    }
    }

     if ($valid_prices !== true)
    {
    // KILL THE SCRIPT
    die($jcart['text']['checkout_error']);
    }
  • 写回答

3条回答 默认 最新

  • dqkelut8423 2009-09-30 10:25
    关注

    The problem is you marking the cart entry as valid if the last array element of $sql_price equals $item_price.

    Rewrite the loop as:

    $valid_prices = true;
    
    foreach($sql_price as $price) {
            $price = $price;
            if ($price !== $item_price) {
                    $valid_prices = false;
            }
    }
    

    To prevent extra iterating, add a break in the inner if to stop the loop after finding an invalid price.

    Or even this:

    $valid_prices = (array_search($price, $sql_price) !== false);
    

    You can have MySQL do all your work for you, even:

    $query = 'select 1 from products where product_name = "' . mysql_real_escape_string($item_name) . '" and product_price = ' . (int)$item_price;
    
    $result = mysql_query($query);
    if (!$result) {
            echo mysql_error();
    }
    
    if (mysql_num_rows($result) > 0) {
            $valid_prices = true;
            echo 'price is good!';
    } else {
            $valid_prices = bad;
            echo 'price is bad!';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大