验证每个产品的折扣代码并分离最终将应用折扣的产品

问题描述 投票:0回答:1

上下文: 我有一个使用 php 和 mysql 并使用 pdo 的在线商店,我需要验证输入到各自产品优惠券代码中的优惠券代码,并为每个产品验证优惠券代码不同。

此处错误: 当我尝试使用正确的优惠券代码捕获产品时,验证返回错误,但优惠券代码已经正确,没有任何错误,优惠券代码验证后只有无效消息

此处参考图片:

alert successfully updated cart,validated coupon codes

correct coupon code for each product

error message after validation result me into error or coupon code empty

完整的 HTML 和 PHP 代码,一些合并在这里

    <?php require_once('header.php'); ?>

<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

<?php
$statement = $pdo->prepare("SELECT * FROM tbl_settings WHERE id=1");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);                            
foreach ($result as $row) {
    $banner_cart = $row['banner_cart'];
}
?>

<?php
$error_message = '';
if(isset($_POST['form1']) || $_SERVER['REQUEST_METHOD'] == 'POST') {

    $i = 0;
    $statement = $pdo->prepare("SELECT * FROM tbl_product");
    $statement->execute();
    $result = $statement->fetchAll(PDO::FETCH_ASSOC);
    foreach ($result as $row) {
        $i++;
        $table_product_id[$i] = $row['p_id'];
        $table_quantity[$i] = $row['p_qty'];
    }
    
    $i=0;
    foreach($_POST['product_id'] as $val) {
        $i++;
        $arr1[$i] = $val;
    }
    $i=0;
    foreach($_POST['quantity'] as $val) {
        $i++;
        $arr2[$i] = $val;
    }
    $i=0;
    foreach($_POST['product_name'] as $val) {
        $i++;
        $arr3[$i] = $val;
    }
    /* aca verificamos el codigo del cupon ingresado con el de cada producto */ 
    /*$statement = $pdo->prepare("SELECT
                                        t1.id_coupon,
                                        t1.coupon_name,
                                        t1.coupon_start_date,
                                        t1.coupon_expire_date,
                                        t1.coupon_code,
                                        t1.coupon_type,
                                        t1.coupon_discount,
                                        t1.validity,
                                        t1.ValorDolarUS,

                                        t2.p_id,
                                        t2.p_name,
                                        t2.p_current_price,
                                        t2.p_qty,
                                        t2.p_featured_photo,
                                        t2.p_description,
                                        t2.p_short_description,
                                        t2.p_feature,
                                        t2.p_condition,
                                        t2.p_return_policy,
                                        t2.p_total_view,
                                        t2.p_is_active,
                                        t2.ecat_id,
                                        t2.ValorDolarUS,
                                        t2.id_coupon

                                        FROM tbl_coupons t1
                                        JOIN tbl_product t2
                                        ON t1.id_coupon = t2.id_coupon WHERE p_id=?
                                ");
    $statement->execute(array($arr1[$i])); 
    $result = $statement->fetchAll(PDO::FETCH_ASSOC);
    foreach ($result as $fila){
        $coupon_code[$i] = $fila['coupon_code'];
    }

    if(empty($_POST['coupon_code_copied'])){
        $validated_coupon_code = "";
    }elseif(isset($_POST['coupon_code_copied'])){
        $coupon_code_copied = $_POST['coupon_code_copied'];
        if($coupon_code_copied == $coupon_code[$i]){
            $validated_coupon_code = "su";
        }else{
            $validated_coupon_code = "er";
        }
    }*/
    /* aca verificamos el codigo del cupon ingresado con el de cada producto */ 
    $allow_update = 1;
    for($i=1;$i<=count(array($arr1));$i++) {
        for($j=1;$j<=count($table_product_id);$j++) {
            if($arr1[$i] == $table_product_id[$j]) {
                $temp_index = $j;
                break;
            }
        }
        if($table_quantity[$temp_index] < $arr2[$i]) {
            $allow_update = 0;
            $error_message .= '"'.$arr2[$i].'" los artículos no están disponibles para "'.$arr3[$i].'"\n';
        } else {
            $_SESSION['cart_p_qty'][$i] = $arr2[$i];
        }
    }
    $error_message .= '\nSe actualizo la cantidad de otros articulos con exito!';
    /*solucion final*/
    $products = $_POST['products'];
    
    // get all the products with their coupons
    $p_id_placeholders = rtrim(str_repeat('?,', count($products)), ',');
    $sql = <<<SQL
            SELECT p.*, c.coupon_code
            FROM tbl_coupons c
            JOIN tbl_product p ON c.id_coupon = p.id_coupon
            WHERE p_id IN ($p_id_placeholders)
            SQL;
    
    // prepare the SQL statement
    $statement = $pdo->prepare($sql);

    // execute and fetch it
    $statement->execute(array_keys($products));
    $result = $statement->fetchAll(PDO::FETCH_ASSOC);

    // re-index the result by product_id
    $result = array_column($result, null, 'p_id');
    
    // validate coupons
    foreach ($products as $product_id => &$product) {
        if ($product['coupon_code'] == '') {
            $product['validated_coupon_code'] = '';
        } elseif ($product['coupon_code'] == $result[$product_id]['coupon_code']) {
            $product['validated_coupon_code'] = 'su';
        } else {
            $product['validated_coupon_code'] = 'er';
        }
    }
    /*solucion final*/
    ?>
    
    <?php if($allow_update == 0): ?>
        <script>alert('<?php echo $error_message; ?>');</script>
    <?php else: ?>
        <script>alert('Se actualizo la cantidad de todos los articulos con exito!');</script>
    <?php endif; ?>
    <?php

}
?>

<div class="page-banner" style="background-image: url(assets/uploads/<?php echo $banner_cart; ?>)">
    <div class="overlay"></div>
    <div class="page-banner-inner">
        <h1><?php echo LANG_VALUE_18; ?></h1>
    </div>
</div>

<div class="page">
    <div class="container">
        <div class="row">
            <div class="col-md-12">

                <?php if(!isset($_SESSION['cart_p_id'])): ?>
                    <?php echo '<lord-icon src="https://cdn.lordicon.com/nlzvfogq.json" trigger="loop" delay="1500" colors="primary:#333333,secondary:#ffc573" stroke="100" style="width:70px;height:70px;">
                    </lord-icon>' . '<h4><b class="text-danger">Carrito de compras vacio!</b>, agregue productos al carrito para poder comprar</h4>'; ?>
                <?php else: ?>
                <form action="" method="post">
                    <?php $csrf->echoInputField(); ?>
                <div class="cart">
                    <table class="table table-responsive">
                        <tr>
                            <th><?php echo LANG_VALUE_7; ?></th>
                            <th><?php echo LANG_VALUE_8; ?></th>
                            <th><?php echo LANG_VALUE_47; ?></th>
                            <th><?php echo LANG_VALUE_157; ?></th>
                            <th><?php echo LANG_VALUE_158; ?></th>
                            <th><?php echo LANG_VALUE_159; ?></th>
                            <th><?php echo LANG_VALUE_55; ?></th>
                            <th class="text-right"><?php echo LANG_VALUE_82; ?></th>
                            <th class="text-right">Valor Descuento</th>
                            <th class="text-center" style="width: 100px;"><?php echo LANG_VALUE_83; ?></th>
                        </tr>
                        <?php
                        $table_total_price = 0;

                        /*$i=0;
                        foreach($_SESSION['cart_p_id'] as $key => $value) 
                        {
                            $i++;
                            $arr_cart_p_id[$i] = $value;
                
                        }

                        $i=0;
                        foreach($_SESSION['cart_size_id'] as $key => $value) 
                        {
                            $i++;
                            $arr_cart_size_id[$i] = $value;
                        }

                        $i=0;
                        foreach($_SESSION['cart_size_name'] as $key => $value) 
                        {
                            $i++;
                            $arr_cart_size_name[$i] = $value;
                        }

                        $i=0;
                        foreach($_SESSION['cart_color_id'] as $key => $value) 
                        {
                            $i++;
                            $arr_cart_color_id[$i] = $value;
                        }

                        $i=0;
                        foreach($_SESSION['cart_color_name'] as $key => $value) 
                        {
                            $i++;
                            $arr_cart_color_name[$i] = $value;
                        }

                        $i=0;
                        foreach($_SESSION['cart_p_qty'] as $key => $value) 
                        {
                            $i++;
                            $arr_cart_p_qty[$i] = $value;
                        }

                        $i=0;
                        foreach($_SESSION['cart_p_current_price'] as $key => $value) 
                        {
                            $i++;
                            $arr_cart_p_current_price[$i] = $value;
                        }

                        $i=0;
                        foreach($_SESSION['cart_p_name'] as $key => $value) 
                        {
                            $i++;
                            $arr_cart_p_name[$i] = $value;
                        }
                        $i=0;
                        foreach($_SESSION['cart_p_featured_photo'] as $key => $value) 
                        {
                            $i++;
                            $arr_cart_p_featured_photo[$i] = $value;
                        }*/
                        ?>
                        <?php
                        $statement = $pdo->prepare("SELECT * FROM tbl_product WHERE p_id=?");
                        $statement->execute(array($_SESSION['cart_p_id'][$i]));
                        $result = $statement->fetchAll(PDO::FETCH_ASSOC);
                        foreach($result as $row){
                                $id_coupon = $row['id_coupon'];
                        }
                        ?>
                        <?php for($i=1;$i<=count($_SESSION['cart_p_id']);$i++): ?>
                        <?php if($id_coupon == '' || $id_coupon == 'NULL'){ ?>
                        <?php 
                        /* aca traemos los datos guardados en el carrito normales si NO tiene DCTO */ 
                        ?>
                        <tr style="esto es lo que se copia NO dcto">
                            <td><?php echo $i; ?></td>
                            <td>
                                <img src="assets/uploads/<?php echo $_SESSION['cart_p_featured_photo'][$i]; ?>" alt="">
                            </td>
                            <td><?php echo $_SESSION['cart_p_name'][$i]; ?></td>
                            <td><?php echo $_SESSION['cart_size_name'][$i]; ?></td>
                            <td><?php echo $_SESSION['cart_color_name'][$i]; ?></td>
                            <?php
                            //SCRIP PARA QUE TRAIGA EL VALOR DEL DOLAR
                            $statement = $pdo->prepare("SELECT ValorDolarUS FROM tbl_product");
                            $statement->execute(array());
                            $result = $statement->fetchAll(PDO::FETCH_ASSOC);                            
                            foreach ($result as $row){
                                $ValorDolarUS = $row['ValorDolarUS'];
                            }
                            ?>
                            <td><?php echo LANG_VALUE_1; ?><?php echo number_format((float)$_SESSION['cart_p_current_price'][$i], 2, '.', ''); ?><span> <i class="flag-icon flag-icon-usa"> </i> USD</span><br>$<?php echo $convertToPesos = number_format($_SESSION['cart_p_current_price'][$i] * $row['ValorDolarUS']); ?><span> <i class="flag-icon flag-icon-col"> </i> COP</span></td>
                            <td>
                                <input type="hidden" name="products[<?php echo $i; ?>][product_id]" value="<?php echo $_SESSION['cart_p_id'][$i]; ?>">
                                <input type="hidden" name="products[<?php echo $i; ?>][product_name]" value="<?php echo $_SESSION['cart_p_name'][$i]; ?>">
                                <input type="number" class="input-text qty text" step="1" min="1" max="" name="products[<?php echo $i; ?>][quantity]" value="<?php echo $_SESSION['cart_p_qty'][$i]; ?>" title="Qty" size="4" pattern="[0-9]*" inputmode="numeric">
                            </td>
                            <td class="text-right">
                                <?php
                                $row_total_price = $_SESSION['cart_p_current_price'][$i]*$_SESSION['cart_p_qty'][$i];
                                $table_total_price = $table_total_price + $row_total_price;
                                ?>
                                <?php echo LANG_VALUE_1; ?><?php echo number_format((float)$row_total_price, 2, '.', ''); ?><span> <i class="flag-icon flag-icon-usa"> </i> USD</span><br>$<?php echo $convertToPesos = number_format($row_total_price * $row['ValorDolarUS']); ?><span> <i class="flag-icon flag-icon-col"> </i> COP</span>
                            </td>
                            <td class="text-center">
                                <a onclick="return confirmDelete();" href="cart-item-delete.php?id=<?php echo $_SESSION['cart_p_id'][$i]; ?>&size=<?php echo $_SESSION['cart_size_id'][$i]; ?>&color=<?php echo $_SESSION['cart_color_id'][$i]; ?>" class="trash"><i style="color: #ffc573" class="fa fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php }else{ ?>
                        <?php 
                        /* pero SI de verdad tiene DCTO,aca traemos los datos con la info del cupon */ 
                        ?>
                        <?php
                        $statement = $pdo->prepare("SELECT
                                                t1.id_coupon,
                                                t1.coupon_name,
                                                t1.coupon_start_date,
                                                t1.coupon_expire_date,
                                                t1.coupon_code,
                                                t1.coupon_type,
                                                t1.coupon_discount,
                                                t1.validity,
                                                t1.ValorDolarUS,
                                                        
                                                t2.p_id,
                                                t2.p_name,
                                                t2.p_current_price,
                                                t2.p_qty,
                                                t2.p_featured_photo,
                                                t2.p_description,
                                                t2.p_short_description,
                                                t2.p_feature,
                                                t2.p_condition,
                                                t2.p_return_policy,
                                                t2.p_total_view,
                                                t2.p_is_active,
                                                t2.ecat_id,
                                                t2.ValorDolarUS,
                                                t2.id_coupon

                                                FROM tbl_coupons t1
                                                JOIN tbl_product t2
                                                ON t1.id_coupon = t2.id_coupon WHERE p_id=?
                                                ORDER BY t1.id_coupon ASC
                                             ");
                        $statement->execute(array($_SESSION['cart_p_id'][$i])); 
                        $result = $statement->fetchAll(PDO::FETCH_ASSOC);
                        foreach ($result as $fila){
                            $id_coupon = $fila['id_coupon'];
                            $coupon_name = $fila['coupon_name'];
                            $coupon_expire_date = date("d-m-Y", strtotime($fila['coupon_start_date']));    
                            $coupon_expire_date = date("d-m-Y", strtotime($fila['coupon_expire_date']));
                            $coupon_code[$i] = $fila['coupon_code'];
                            $coupon_type = $fila['coupon_type'];
                            $coupon_discount = $fila['coupon_discount'];
                            $validity = $fila['validity'];

                            $p_id = $fila['p_id'];
                            $p_name = $fila['p_name'];
                            $coupon_name = $fila['coupon_name'];
                            $p_current_price = $fila['p_current_price'];
                            $p_qty = $fila['p_qty'];
                            $p_featured_photo = $fila['p_featured_photo']; 
                            $ValorDolarUS = $fila['ValorDolarUS'];
                        }
                        ?>
                        <tr style="esto es lo que se copia SI dcto">
                            <td><?php echo $i; ?></td>
                            <td>
                                <img src="assets/uploads/<?php echo $_SESSION['cart_p_featured_photo'][$i]; ?>" alt="">
                            </td>
                            <td><?php echo $_SESSION['cart_p_name'][$i]; ?></td>
                            <td><?php echo $_SESSION['cart_size_name'][$i]; ?></td>
                            <td><?php echo $_SESSION['cart_color_name'][$i]; ?></td>
                            <?php
                            //SCRIP PARA QUE TRAIGA EL VALOR DEL DOLAR
                            $statement = $pdo->prepare("SELECT ValorDolarUS FROM tbl_product");
                            $statement->execute(array());
                            $result = $statement->fetchAll(PDO::FETCH_ASSOC);                            
                            foreach ($result as $row){
                                $ValorDolarUS = $row['ValorDolarUS'];
                            }
                            ?>
                            <td><?php echo LANG_VALUE_1; ?><?php echo number_format((float)$_SESSION['cart_p_current_price'][$i], 2, '.', ''); ?><span> <i class="flag-icon flag-icon-usa"> </i> USD</span><br>$<?php echo $convertToPesos = number_format($_SESSION['cart_p_current_price'][$i] * $row['ValorDolarUS']); ?><span> <i class="flag-icon flag-icon-col"> </i> COP</span></td>
                            <td>
                                <input type="hidden" name="products[<?php echo $i; ?>][product_id]" value="<?php echo $_SESSION['cart_p_id'][$i]; ?>">
                                <input type="hidden" name="products[<?php echo $i; ?>][product_name]" value="<?php echo $_SESSION['cart_p_name'][$i]; ?>">
                                <input type="number" class="input-text qty text" step="1" min="1" max="" name="products[<?php echo $i; ?>][quantity]" value="<?php echo $_SESSION['cart_p_qty'][$i]; ?>" title="Qty" size="4" pattern="[0-9]*" inputmode="numeric">
                            </td>
                            <td class="text-right">
                                <?php
                                $row_total_price = $_SESSION['cart_p_current_price'][$i]*$_SESSION['cart_p_qty'][$i];
                                $table_total_price = $table_total_price + $row_total_price;
                                ?>
                                <?php echo LANG_VALUE_1; ?><?php echo number_format((float)$row_total_price, 2, '.', ''); ?><span> <i class="flag-icon flag-icon-usa"> </i> USD</span><br>$<?php echo $convertToPesos = number_format($row_total_price * $row['ValorDolarUS']); ?><span> <i class="flag-icon flag-icon-col"> </i> COP</span>
                            </td>
                            <td style="ESTE ES" class="text-right">
                            <?php
                            /* aca verificamos el codigo del cupon ingresado con el de cada producto */
                            if($validated_coupon_code == ""){
                                echo '
                                <script type="text/javascript">
                                swal({
                                title: "Codigo Cupon Vacio",
                                text: "Si  el codigo de cupon(es distinto por cada producto) esta vacio,no tendras DCTO",
                                icon: "error",
                                button: "OK,lo comprendo",
                                });
                                </script>';
                            }elseif($validated_coupon_code == "er"){
                                echo '
                                <script type="text/javascript">
                                swal({
                                title: "Codigo Cupon Incorrecto",
                                text: "Si  el codigo de cupon(es distinto por cada producto) no es valido,no tendras DCTO",
                                icon: "warning",
                                button: "OK,lo comprendo y revisare",
                                });
                                </script>';
                            }elseif($validated_coupon_code == "su"){
                                echo '
                                <script type="text/javascript">
                                swal({
                                title: "Codigo Cupon Validado con Exito",
                                text: "Veras el DCTO aplicado a cada producto por cada codigo de DCTO colocado",
                                icon: "success",
                                button: "OK,revisare mi DTCO al finalizar la compra",
                                });
                                </script>';
                            }
                            /* aca verificamos el codigo del cupon ingresado con el de cada producto */ ?>   
                            <?php echo "$" . $DiscountedValueUS . "<span> <i class='flag-icon flag-icon-usa'> </i> USD</span>" . "<br>" . "$" . $DiscountedValueCOP . "<span> <i class='flag-icon flag-icon-col'> </i> COP</span>" . "<br>" ; ?> 
                            <input type="text" class="input-text text" name="products[<?php echo $i; ?>][coupon_code]" placeholder="escriba el codigo de DCTO">    
                            </td>
                            <td class="text-center">
                                <a onclick="return confirmDelete();" href="cart-item-delete.php?id=<?php echo $_SESSION['cart_p_id'][$i]; ?>&size=<?php echo $_SESSION['cart_size_id'][$i]; ?>&color=<?php echo $_SESSION['cart_color_id'][$i]; ?>" class="trash"><i style="color: #ffc573" class="fa fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php } ?>
                        <?php endfor; ?>
                        <tr style="border-top: 1px solid #ddd;">
                            <th colspan="7" class="total-text"><span class="text-warning txt_aviso txt_aviso_p_producto"><i class="fa fa-exclamation-circle"></i>veras el DCTO luego de<br> validar el codigo y la compra!</span> Total</th>
                            <th class="total-amount"><?php echo LANG_VALUE_1; ?><?php echo number_format((float)$table_total_price, 2, '.', ''); ?><span> <i class="flag-icon flag-icon-usa"> </i> USD</span><br>$<?php echo $convertToPesos = number_format($table_total_price * $row['ValorDolarUS']); ?><span> <i class="flag-icon flag-icon-col"> </i> COP</span></th>
                            <th></th>
                        </tr>
                    </table> 
                </div>

                <div class="cart-buttons">
                    <style type="text/css">
                        .info:hover{
                            cursor: help;
                        }
                    </style>
                    <ul>
                        <li>
                            <button rel="tooltip" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="Debes actualizar aqui para que tomen los cambios en el carrito.." style="background: #333;color: white;border-radius: 0px !important;border: none !important;height: 80px" class="info btn btn-lg btn-primary" type="submit" name="form1"><i style="color: #ffc573;vertical-align: middle;padding-right: 15px;padding-bottom: 0px" class="fa fa-lg fa-cart-arrow-down"></i>  <?php echo LANG_VALUE_20; ?><hr style="border-top: 1px solid #ffc573;margin-top: 5px;margin-bottom: -15px;"><span>Verificar Codigo DCTO <lord-icon src="https://cdn.lordicon.com/waumjsnp.json" trigger="loop" colors="primary:#ffffff,secondary:#ffc573" style="width:70px;height:70px"></lord-icon></span></button>
                        </li>
                        <li>
                                <button style="background: #333;color: white;border-radius: 0px !important;border: none !important;" class="btn btn-lg btn-primary"><i style="color: #ffc573;vertical-align: middle;padding-right: 0px;" class="fa fa-lg fa-shopping-bag"></i>
                                <a href="index.php"><?php echo LANG_VALUE_85; ?></a></button>
                        </li>
                        <li>
                            <button style="background: #333;color: white;border-radius: 0px !important;border: none !important;" class="btn btn-lg btn-primary"><i style="color: #ffc573;vertical-align: middle;padding-right: 0px;" class="fa fa-lg fa-credit-card"></i>
                            <a href="checkout.php"><?php echo LANG_VALUE_23; ?></a></button>
                        </li>
                    </ul>
                </div>
                </form>
                <?php endif; ?>

                

            </div>
        </div>
    </div>
</div>


<?php require_once('footer.php'); ?>
php mysql pdo
1个回答
1
投票

我将从解决您命名表单输入的方式开始。您当前的表单看起来像这样(删除了所有不相关的标记):

<form action="" method="post">

    <input type="hidden" name="product_id[]" value="3">
    <input type="hidden" name="product_name[]" value="some name">
    <input type="number" name="quantity[]" value="3">
    <input type="text"   name="coupon_code_copied" value="" placeholder="escriba el codigo de DCTO">

    <input type="hidden" name="product_id[]" value="7">
    <input type="hidden" name="product_name[]" value="some other name">
    <input type="number" name="quantity[]" value="2">
    <input type="text"   name="coupon_code_copied" value="" placeholder="escriba el codigo de DCTO">

    <input type="submit" name="action" value="Verificar Codigo DCTO">

</form>

注意每个产品的前三个输入如何以

[]
结尾的,因此在 PHP 端的请求处理期间数据被构建到数组中,但两个
coupon_code_copied
输入却没有。这会导致您在 PHP 端只有一个优惠券代码,因为第二个代码会覆盖第一个代码。
$_POST
数组的转储看起来像:

Array
(
    [product_id] => Array
        (
            [0] => 3
            [1] => 7
        )

    [product_name] => Array
        (
            [0] => some name
            [1] => some other name
        )

    [quantity] => Array
        (
            [0] => 3
            [1] => 2
        )

    [coupon_code_copied] => X-690
    [action] => Verificar Codigo DCTO
)

将这些更改为

coupon_code[]
会导致它们作为数组通过,就像其他字段一样:

Array
(
    ...

    [coupon_code] => Array
        (
            [0] => X-689
            [1] => X-690
        )

    [action] => Verificar Codigo DCTO
)

让这些都作为不相关的数组通过并没有真正意义,我建议使用

product_id
(或者
$i
迭代器变量,如果你愿意)作为
key
:

<form action="" method="post">

    <input type="hidden" name="products[3][product_name]" value="some name">
    <input type="number" name="products[3][quantity]" value="3">
    <input type="text"   name="products[3][coupon_code]" value="" placeholder="escriba el codigo de DCTO">

    <input type="hidden" name="products[7][product_name]" value="some other name">
    <input type="number" name="products[7][quantity]" value="2">
    <input type="text"   name="products[7][coupon_code]" value="" placeholder="escriba el codigo de DCTO">

    <input type="submit" name="action" value="Verificar Codigo DCTO">

</form>

使用此命名约定,

$_POST
数组将类似于:

Array
(
    [products] => Array
        (
            [3] => Array
                (
                    [product_name] => some name
                    [quantity] => 3
                    [coupon_code] => X-689
                )

            [7] => Array
                (
                    [product_name] => some other name
                    [quantity] => 2
                    [coupon_code] => X-690
                )

        )

    [action] => Verificar Codigo DCTO
)

然后当收到

$_POST
你的优惠券验证变成这样的:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $products = $_POST['products'];

    // get all the products with their coupons
    $p_id_placeholders = rtrim(str_repeat('?,', count($products)), ',');
    $sql = <<<SQL
            SELECT p.*, c.coupon_code
            FROM tbl_coupons c
            JOIN tbl_product p ON c.id_coupon = p.id_coupon
            WHERE p_id IN ($p_id_placeholders)
            SQL;

    // prepare the SQL statement
    $statement = $pdo->prepare($sql);

    // execute and fetch it
    $statement->execute(array_keys($products));
    $result = $statement->fetchAll(PDO::FETCH_ASSOC);

    // re-index the result by product_id
    $result = array_column($result, null, 'p_id');

    // validate coupons
    foreach ($products as $product_id => &$product) {
        if ($product['coupon_code'] == '') {
            $product['validated_coupon_code'] = '';
        } elseif ($product['coupon_code'] == $result[$product_id]['coupon_code']) {
            $product['validated_coupon_code'] = 'su';
        } else {
            $product['validated_coupon_code'] = 'er';
        }
    }
}

希望上面的代码足够清晰,您可以将其合并到您的代码中。

© www.soinside.com 2019 - 2024. All rights reserved.