Search code examples
phpmysqlpdo

validate discount codes for each product and separate the products that will finally have a discount applied


Context: I have an online store with php and mysql and using pdo,i need to validate coupon code entered into their respective product coupon code and validate it for each product the coupon code its diferent.

Error here: when i try to catch product with correct coupon code the validation return me error,but the coupon code already correct,doesnt have any error,only invalid message after coupon code validation

References images here:

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

COMPLETE HTML AND PHP CODE,SOME MERGED HERE

    <?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'); ?>

Solution

  • I'll start by addressing the way you are naming your form inputs. You current form looks something like this (all irrelevant markup removed):

    <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>
    

    Notice how the first three inputs for each product have names ending in [] so the data is built into an array during request processing on the PHP side, but the two coupon_code_copied inputs do not. This leads to you only having one coupon code on the PHP side as the second overwrites the first. A dump of your $_POST array will look something like:

    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
    )
    

    Changing these to coupon_code[] would lead to them coming through as an array, like the other fields:

    Array
    (
        ...
    
        [coupon_code] => Array
            (
                [0] => X-689
                [1] => X-690
            )
    
        [action] => Verificar Codigo DCTO
    )
    

    Having these all coming through as unrelated arrays does not really make sense, and I suggest an alternative approach using the product_id (or $i iterator var if you prefer) as the 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>
    

    With this naming convention the $_POST array will look somethin like:

    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
    )
    

    Then when receiving the $_POST your coupon validation becomes something like:

    $error_message = '';
    if(isset($_POST['form1'])) {
    
        $products = $_POST['products'];
    
        // get all the products with their coupons and quantity values for validation
        $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_column($products, 'product_id'));
        $result = $statement->fetchAll(PDO::FETCH_ASSOC);
    
        // re-index the result by product_id
        $result = array_column($result, null, 'p_id');
    
        foreach ($products as $i => &$product) {
    
            // validate coupons
            if ($product['coupon_code'] == '') {
                $product['validated_coupon_code'] = '';
            } elseif ($product['coupon_code'] == $result[$product['product_id']]['coupon_code']) {
                $product['validated_coupon_code'] = 'su';
            } else {
                $product['validated_coupon_code'] = 'er';
            }
    
            // validate quantity
            if ($product['quantity'] > $result[$product['product_id']]['p_qty']) {
                $error_message .= '"' . $product['quantity'] . '" los artículos no están disponibles para "' . $product['product_name'] . '"\n';
            } else {
                $_SESSION['cart_p_qty'][$i] = $product['quantity'];
            }
        }
    
        if ($error_message) {
            $error_message .= '\nSe actualizo la cantidad de otros articulos con exito!';
        } else {
            $error_message = 'Se actualizo la cantidad de todos los articulos con exito!';
        }
    
        echo "<script>alert('$error_message');</script>";
    
    }
    

    When you display your coupon_code messages, instead of $validated_coupon_code you should be using $products[$i]['validated_coupon_code'], as it is set per product.

    Hopefully, the above code is clear enough that you are able to incorporate it into your code.