Search code examples
phparraysloopsprepared-statementsql-insert

Insert 4-column rows into database table from a flat array with a size divisible by four


I have an array like below which is generated by exploding a user-supplied string:

// $array = explode(',' $_POST['arrCheckTrans']);
$array = [
    '098A',
    'mike',
    'Street17',
    'LA',
    '07AA',
    'steve',
    'Street14',
    'LA'
];

I need to isolate four elements at a time and use those sets of values to make iterated INSERT queries.

Below is my code:

if ($_POST['action'] == "checktransfertmp") {

   $arrCheckTrans = $_POST['arrCheckTrans'];
   
   $trans = explode(",", $arrCheckTrans);
   
   $length = count($trans);
   for ($i = 0; $i < $length; $i++) {
       print $trans[$i];
   }
}

How can I make run insert queries for each set of values?


Solution

  • You need to use array_chunk.

    $chunks = array_chunk($trans, 4);
    foreach ($chunks as $chunk) {
      // Build your insert string
    }
    

    To build your insert string (rather than doing multiple queries) you could do something like:

    $insertString  = 'INSERT INTO myTable(col1, col2, col3, col4) VALUES ';
    
    foreach ($chunks as $chunk) {
        $insertString .= ' (' . implode(', ', array_map('escape_function', $chunk)) . ',';
    }
    
    $insertString = substr($insertString, 0, -1);
    
    • Note to use a real escape function like mysqli_real_escape_function, or array($pdoLink, 'escape').