0

I have an array like so:

$array = array(value1,value2,value3,value4,value5,value6,value7,value8,value9,value10,value11,value12);

What i need to do is insert the array value into a database
row one would have value1,value2,value3,value4

row two would have value5,value6,value7,value8

row three would have value9,value10,value11,value12

I was thinking i would need a for loop. Can anyone help on this? thanks

for($x=0; $x<$count1; $x++)
{


}
2
Contributors
3
Replies
22
Views
4 Years
Discussion Span
Last Post by broj1
1

Something like (not tested):

// check if the number of fields is multiple of 4
if(count($array) % 4 == 0) {
    // start building the query
    $query = 'INSERT INTO yourdatabase (`field1`, `field2`, `field3`, `field4`) VALUES ';
    // add values to the query
    for($x = 0; $x < $count($array); $x += 4) {
        // add a set of four values to the query
        $query .= "('{$array[$x]}','{$array[$x + 1]}','{$array[$x + 2]}','{$array[$x + 3]}'),";
    }
    // get rid of the last comma in the query
    $query = rtrim($query, ',');
    // run the query
    ....
}

Edited by broj1

0

BTW: the line 6 in the above code should be:

for($x = 0; $x < count($array); $x += 4) {

and line 8 should be:

$query .= "('" . $array[$x] . "','" . $array[$x + 1] . "','" . $array[$x + 2] . "','" . $array[$x + 3] . "'),";

I was typing too fast :-)

Edited by broj1

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.