0

I'm trying to submit an array data from my form, but before submission I want that array value to be compared with the value I have from the database. if one among the value in the array is greater than the one I have in the database loop should be terminated and print the output otherwise the form should be submitted.

But the problem is both if and else and are tested and both of them executed.

MY FORM INPUT user Form

MY PHP CODE

if(isset($_POST['btn_action'])){

    $material_id = $_POST['material_added_id'];
    $material_issued = $_POST['material_isseud_weight']; //userInput--Array
    $unit_type = $_POST['unit_type'];
    $product_id = $_POST['product_id'];
    $ricip_name = $_POST['ric'];
    $count = 0;
    

    for($count; $count < count($material_id); $count++) {

        //fetching data from DB
        $qry = "SELECT * FROM material_added_tb WHERE material_added_id = $material_id[$count]";
        $statement = $conn->prepare($qry);
        $statement->execute();
        $result = $statement->fetchAll(PDO::FETCH_ASSOC);

        foreach($result as $value) {
            $material_weight = $value['material_weight'];
            $material_name = $value['material_added_name'];
        }

        //compare the userArray data with the data from DB
        if($material_issued[$count] > $material_weight) {
            
            ?>
                <script>
                alert('<?php echo $material_name . " is Out of Stock " ?>');
                // window.location.href="../manufacture.php";
                </script>
            <?php 
          
        } else {
            
            echo "submit the form";
        }
        
    }
}

    
amHafidhJr
  • 13
  • 3
  • 3
    (Possible) side note: Do not use string interpolation or concatenation to get values into SQL queries. That's error prone and might make your program vulnerable to SQL injection attacks. Use parameterized queries. See ["How to include a PHP variable inside a MySQL statement"](https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement) and ["How can I prevent SQL injection in PHP?"](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – sticky bit Oct 27 '21 at 08:59
  • on submit button click call ajax and based on ajax response take actions like display message or submit form. – PHP Hupp Technologies Oct 27 '21 at 09:38

1 Answers1

0

If you want to check the values before submitting the form, you have to do it in javascript (+ maybe Ajax, if you want to check them exactly at the moment the button is clicked).

I assume that the php code you attached is precisely the one that corresponds to an Ajax request that validate the values, but in that case, you should send a json reply back to the browser instead of an alert.