Why is PHP Inserting Twice For MYSQL Each Query

  mysql, php

So basically, the problem is when i hit submit, PHP is I don’t why inserting same insert query twice e.g if i write 5th and hit submit, 5th will be there twice in the database. How can i fix it ?

HTML:

 <div class="col-md-3">
 <form action="" method="POST" name="class_name">
 <div class="input_fields_wrap">
                                <input type="text" class="form-control mb-3" id="classname" name="class[]"
                                  placeholder="Enter Class Name" required>
                              </div>
                              <button class="add_field_button btn btn-secondary mb-2">Add More Fields 2</button>
                              <br>
                              <button type="submit" value="Submit" class="btn btn-success">Submit</button>
                            </form>
                          </div>

Php:

 if(isset($_POST['class'])) {
                       
                        
                        
    //Repetitive Insert command on each row  
    function addstandard($array)  
    {  
        global $connection;
        $nullvalue = 'NULL';
         if(is_array($array))  
         {  
              foreach($array as $row => $value)  
              {  
                   $class_name = mysqli_real_escape_string($connection, $value);  
                   $sql = "INSERT INTO standard(class_id,class_name,class_section,class_strength,class_teacher_assigned) VALUES ($nullvalue,'".$class_name."', $nullvalue,$nullvalue,$nullvalue)"; 
                   //echo $sql; 
                   mysqli_query($connection, $sql);  
                   if (mysqli_query($connection, $sql)) {
                    echo json_encode(array("statusCode"=>200));                     
                } 
                else {
                    echo json_encode(array("statusCode"=>201));
                }
              }  
         }  
    } 

 $standard = $_POST['class'];
 addstandard($standard); 

                                             
                        }

Source: Ask PHP

LEAVE A COMMENT