Insert database rows from columns of data from associative array of indexed arrays



PHP Snippet 1:

for($i=0; $i<count($works['type']); $i++) {
    $query = "INSERT INTO `works` (`type`, `decsripion`, `hours`, `amount`) VALUES ('{works[type][$i]}', '{works[description][$i]}', '{works[hours][$i]}', '{works[amount][$i]}')";
    mysql_query($query);
}

PHP Snippet 2:

<?php
$works = array('type'=>array(1,5),'description'=>array(2,6),'hours'=>array(3,7),'amount'=>array(4,8));
    $insert_query = 'INSERT INTO works(type,description,hours,amount) values ';
    for($i=0; $i<count($works['type']); $i++) {
                $insert_query .= "('".$works['type'][$i]."','".$works['description'][$i]."','".$works['hours'][$i]."','".$works['amount'][$i]."')," ;

    }

    $query = rtrim($insert_query, ',');
    //echo $query;
    if(!mysqli_query($con,$query)){
        die('Error: ' . mysqli_error($con));
    }else{
        echo "record added";
    }

PHP Snippet 3:

$works = [
    'type' => [1, 5],
    'description' => [2, 6],
    'hours' => [3, 7],
    'amount' => [4, 8]
];

if (!empty($works['type'])) {
    $sql = "INSERT INTO works (type, description, hours, amount)
            VALUES (?,?,?,?)";
    $stmt = $mysqli->prepare($sql);
    for ($i = 0, $count = count($works['type']); $i < $count; ++$i) {
        $stmt->bind_param(
            "iiii",
            $works['type'][$i],
            $works['description'][$i],
            $works['hours'][$i],
            $works['amount'][$i]
        );
        $stmt->execute();
    }
}
var_export($mysqli->query("SELECT * FROM works")->fetch_all(MYSQLI_ASSOC));

PHP Snippet 4:

array (
  0 => 
  array (
    'id' => '1',
    'type' => '1',
    'description' => '2',
    'hours' => '3',
    'amount' => '4',
  ),
  1 => 
  array (
    'id' => '2',
    'type' => '5',
    'description' => '6',
    'hours' => '7',
    'amount' => '8',
  ),
)