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


I have an array called $works which looks like this:

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

I need to send all values to Database (MySQL) in two iterations. Something like:

INSERT INTO `works` (`type`, `description`, `hours`, `amount`) VALUES (works[type][0], works[decsription][0], works[hours][0], works[amount][0]);

INSERT INTO `works` (`type`, `description`, `hours`, `amount`) VALUES (works[type][1], works[description][1], works[hours][1], works[amount][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]}')";

That is provided that you have already connected and selected a database.
There are better ways of doing this but this depends on framework you are using. For example, you might want to escape these values before trying to insert them into database.

Answered By – Tim Hysniu

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published