1

I am using the following script to try and insert new rows to my database. For some reason only the first row is inserted, it is like the other rows are not posted. I can't find what is going wrong, I get no error logs and see no typos nor differences..

Does someone know what I am doing wrong?

The PHP & SQL:

if(isset($_POST['submitnewacc']))
{
    for($i=0;$i<count($_POST['slno']);$i++)
    {
        $name = $_POST['name'][$i];
        $email = $_POST['accmail'][$i];
        $password = $_POST['password'][$i];
        $bullets = $_POST['bullets'][$i];
        $notes = $_POST['notes'][$i];
        $rang = $_POST['rang'][$i];
        $betaald = $_POST['betaald'][$i];
        $paydate = $_POST['paydate'][$i];
        
        if ( trim($name) != '') { $nameacc = trim($name); }
        if ( trim($email) != '') { $emailacc = trim($email); }
        if ( trim($password) != '') { $passwordacc = trim($password); }
        if($betaald =='') { $betaald = 'No'; }
        
        if($nameacc != '' && $emailacc != '' && $passwordacc != '' && $bullets >= '0')
        {

            $stmt16 = $mysqli->prepare("
            INSERT INTO account (name,email,password,bullets,rang,betaald,testpay,door,group_name,notes)
                                VALUES (trim(?),trim(?),trim(?),trim(?),trim(?),trim(?),trim(?),trim(?),trim(?),trim(?))");
            $stmt16->bind_param('ssssssssss',$nameacc,$emailacc,$passwordacc,$bullets,$rang,$betaald,$paydate,$usernamesession,$groupname,$notes);  
            $stmt16->execute();
            $stmt16->close();
     
            if($stmt16 == TRUE)
            {
                $log_page = "Newaccount";
                $log_account = filter_var($name, FILTER_SANITIZE_STRING);
                $datum = filter_var(date ("Y-m-d H:i:s"), FILTER_SANITIZE_STRING); 
                $message = filter_var($usernamesession." added a new account: ".$log_account." (rang: ".$rang.", bullets: ".$bullets.", 
    , paying: ".$betaald.", notes: ".$notes.")", FILTER_SANITIZE_STRING);
                $userip = htmlspecialchars(filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_SANITIZE_STRING)); 

                $stmt12 = $mysqli->prepare("INSERT INTO logs (user_ID, log_action, log_time, log_ip, log_account, log_page, 
    log_owner, log_group) VALUES (trim(?),trim(?),trim(?),trim(?),trim(?),trim(?),trim(?),trim(?))");
                $stmt12->bind_param('isssssss',$userid,$message,$datum,$userip,$log_account,$log_page,$usernamesession,$groupname);  
                $stmt12->execute();
                $stmt12->close();
    
                $_SESSION['addacc'] = '<p><b><font color="orange">You have succesfully added the accounts to the database!</p>
    </font></b></ br>' ;
    
                header('Location: ' . 'lijst_myaccounts.php');
                exit(); 
            }

            //echo '<div class="alert alert-success" role="alert">Submitted Successfully</div>';
        }
        else
        {
            echo '<div class="alert alert-danger" role="alert">Error Submitting in Data</div>';
        }
    }
}

The form

<table class="userprof" align='left' >
    <tr>
    <td class="footer">Options: </td>
    <td class="footer" >
    <button type="button" name="addrow" id="addrow" class="example_e">Add New Row</button>
    </td>
    </tr> </table><br /><br />


<br/><br/><br/>
<script src="java/sorttable.js"></script>
<script src="js/jquery.min.js"></script> 
<script src="js/bootstrap.min.js"></script>


<form class="form-horizontal"action="<?php htmlspecialchars($filterpage); ?>" method="post">
  <div class="divTable blueTable" style="float:left !important;">
    <div class="divTableHeading">
      <div class="divTableRow">
        <div class="divTableHead" style="width:0px !important;"></div>
        <div class="divTableHead">Account Name</div>
        <div class="divTableHead">Emailadress</div>
        <div class="divTableHead">Password</div>
        <div class="divTableHead">Rang</div>
        <div class="divTableHead">Bullets</div>
        <div class="divTableHead">Notes</div>
        <div class="divTableHead">Paying</div>
        <div class="divTableHead">Paying untill</div>
        <div class="divTableHead" style="width:2px !important;"></div>
      </div>
    </div>
    <div class="divTableBody">
      <div class="divTableRow">
        <div class="divTableCell"><input type="hidden" style="width:2px !important;" class="form-control sl" 
        name="slno[]" id="slno" value="1" readonly=""></div>
        
        <div class="divTableCell"><input type="text" style="width:190px !important;font-weight: normal !important;"
         class="form-control" name="name[]" id="acc_name" placeholder="Enter Account Name" required minlength="3" maxlength="150"></div>
         
         <div class="divTableCell"><input type="email" style="width:210px !important;font-weight: normal !important;"
         class="form-control" name="accmail[]" id="acc_email" placeholder="mail@mail.nl" required minlength="3" maxlength="150"
         ></div>
         
         <div class="divTableCell"><input type="text" style="width:130px !important;font-weight: normal !important;"
         class="form-control" name="password[]" id="acc_pass" placeholder="Enter Password" required minlength="3" maxlength="50"></div>
         
        <div class="divTableCell">
          <select name="rang[]" id="rang_acc" style="width:80px !important;font-weight: normal !important;" class="form-control">
            <option value="Bacteria">Bacteria</option>
            <option value="Low Life">Low Life</option>
            <option value="Apprentice">Apprentice</option>
            
          </select>
        </div>
        <div class="divTableCell"><input type="number" style="width:60px !important; font-weight: normal !important;" 
        required pattern="[0-9]+" value="0" onClick="this.select()" name="bullets[]" id="acc_bullets" class="form-control"></div>
        
        <div class="divTableCell"><input type="text" name="notes[]" id="acc_notes" maxlength="250" 
        style="width:210px !important; font-weight: normal !important;" placeholder="OPTIONAL enter notes" class="form-control"/></div>
        
        <div class="divTableCell">
        <label class="switch">
        
        <input type="checkbox" name="betaald[]" id="acc_betaald"  value="Yes" checked/>
        <div class="slider round">
        <span class="on">Yes</span>
        <span class="off">No</span>
        </div>
        </label></div>
        
        <div class="divTableCell"><input type="text" name="paydate[]" value="2020-01-01" 
        style="width:100px !important; font-weight: normal !important; color:#F00" 
        id="acc_paydate" required pattern="[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])"  
    class="form-control" /></div>
        <div class="divTableCell"></div>
       
      </div>
      
    </div>
  </div>
  <br/>

  <button type="submit" name="submitnewacc" class="example_e">Add account(s) to database!</button>
</form>

The Script

<script type="text/javascript">
const tableRow = (i) => {return `
    <div class="divTableRow">
      <div class="divTableCell" >
        <input type="hidden" class="form-control sl" style="width:2px !important;" name="slno[]" value="${ i }" readonly="">
      </div>
      <div class="divTableCell">
        <input type="text" style="width:190px !important;font-weight: normal !important;" 
        class="form-control" name="name[]" id="acc_name${ i }" placeholder="Enter Account Name" 
        required minlength="3" maxlength="150" >
      </div>
      <div class="divTableCell"><input type="email" style="width:210px !important;font-weight: normal !important;"
         class="form-control" name="accmail[]" id="acc_email${ i }" placeholder="mail@mail.nl" required minlength="3" 
         maxlength="350" ></div>
         
         <div class="divTableCell"><input type="text" style="width:130px !important;font-weight: normal !important;"
         class="form-control" name="password[]" id="acc_pass${ i }" placeholder="Enter Password" required minlength="3" maxlength="150"
       ></div>
         
      <div class="divTableCell">
        <select name="rang[]" id="rang_acc${ i }" style="width:80px !important;font-weight: normal !important;"
         class="form-control">
          <option value="Bacteria">Bacteria</option>
          <option value="Low Life">Low Life</option>
          <option value="Apprentice">Apprentice</option>
      
        </select>
      </div>
      
      <div class="divTableCell"><input type="number" style="width:60px !important; font-weight: normal !important;" 
        required pattern="[0-9]+" value="0" onClick="this.select()" name="bullets[]" id="acc_bullets${ i }" class="form-control"></div>
        <div class="divTableCell"><input type="text" name="notes[]" id="acc_notes${ i }" maxlength="250" 
        style="width:210px !important; font-weight: normal !important;" placeholder="OPTIONAL enter notes" class="form-control"/></div>
        
      <div class="divTableCell">
        <label class="switch">
        
        <input type="checkbox" name="betaald[]" id="acc_betaald${ i }"  value="Yes" checked/>
        <div class="slider round">
        <span class="on">Yes</span>
        <span class="off">No</span>
        </div>
        </label></div>
      
      <div class="divTableCell"><input type="text" name="paydate[]" id="acc_paydate${ i }" value="2020-01-01"
         style="width:100px !important; font-weight: normal !important; color:#F00"
         required pattern="[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])" class="form-control" /></div>
    
      <div class="divTableCell">
        <input type="button" class="btnRemove example_b" value="Delete"/>
      </div>
    </div>
  `
}

$('#addrow').click(function() {
  var length = $('.sl').length;
  var i = parseInt(length) + parseInt(1);
  var newrow = $('.divTableBody').append(tableRow(i));
});

// Removing event here
$('body').on('click', '.btnRemove', function() {
  $(this).closest('div').parent().remove()
});
    </script>
ADyson
  • 57,178
  • 14
  • 51
  • 63
  • " it is like the other rows are not posted"...you need to debug a bit more then, to be sure. Use your browser's developer tools to see what actually _is_ posted. And add some logging to your PHP to see what the $_POST data looks like, and what path the code takes, how many insert queries are actually executed, whether any of them fail, etc. – ADyson Jan 11 '21 at 23:07
  • Just to be clear. I am no profesional developer. I am new and trying to learn while doing. I am known with checking console but i have no idea where to find what is posted. The row that is posted is the one that is not adabted by the script to create more rows. – newusertomysqli12 Jan 11 '21 at 23:16
  • These instructions are for Chrome but most other browsers' tools are similar: Load your form. Open the developer tools. Go to the Network tab. Ensure the "preserve log" box is ticked. Then add some rows, fill in some data, and submit the form. You should see a POST request to your .php script. Click on the request. In the "Headers" tab of the info which appears, scroll right to the bottom, and you should see a "Form data" section. Look in there. – ADyson Jan 11 '21 at 23:16
  • On the PHP side, you can use `var_dump($_POST);` to make PHP output a view of the data it receives (it _should_ be the same data as the browser shows is being submitted). – ADyson Jan 11 '21 at 23:20
  • Thank you. Did what you said. Both are showing the actual posts i made.. Now what to do .. – newusertomysqli12 Jan 11 '21 at 23:29
  • Next is to debug the PHP and SQL – ADyson Jan 11 '21 at 23:35
  • Where to begin ? I get no errors on my server log.. – newusertomysqli12 Jan 11 '21 at 23:39
  • Make sure PHP error logging is configured correctly, and also that mysqli is configured to report errors when something goes wrong with a SQL query. See these two guides for detailed setup info: https://stackify.com/php-error-logs-guide/ (php error logging/reporting) and https://stackoverflow.com/a/14578644/5947043 (mysqli error handling) – ADyson Jan 11 '21 at 23:49
  • Those are all set. That is why i posted here, i cant find the problem.. – newusertomysqli12 Jan 11 '21 at 23:53
  • You could also add some simple logging to the PHP code in various places using the var_dump or echo commands - so you can check the values of variables, and ensure that the code is taking the path you expect (e.g. ensure it loops the right amount of times, and enters the right `if` blocks and so on). Anything to try and narrow down the issue to a smaller area. – ADyson Jan 11 '21 at 23:55
  • But actually, you know something...now that I added the formatting to your code so I could see the if statements and the brackets properly, the problem has become more obvious: `header('Location: ' . 'lijst_myaccounts.php'); exit(); ` is the problem. This code is within your `for` loop. So clearly, the first time it loops, it will run the exit() command, and never execute the subsequent loops. I expect this code really ought to be placed after your loop ends. This really shows the value of clearly-formatted code :-) – ADyson Jan 11 '21 at 23:57
  • Ok, well tried all that. All it does not do is insert the rows after the next ones. So I assume it must be something with the for or insert than. But i have not enough knowledge yet to determine that.. – newusertomysqli12 Jan 11 '21 at 23:58

1 Answers1

0

This code:

header('Location: ' . 'lijst_myaccounts.php');
exit(); 

needs to be moved to after your for loop ends. Otherwise it will exit the script during the first iteration of the loop.

ADyson
  • 57,178
  • 14
  • 51
  • 63