views:

203

answers:

5

I have a PHP 2D array, many keys, each with one value, I need to put this into a MySQL database.

The database has 8 fields. Eg. Field1, Field2, Field3, etc.

I am trying to ensure value1 => field1, value2 =>field2, value3 => field3 and so on, when one record is full (i.e. after 8 values) a new record should be created for the next 8 values and so on.

I am aware that the 1st, 9th, 17th, 26th values etc, will need an insert statement and the intermediate values will be an update statement.

What is the best way of going about this?

+1  A: 

Simplest to understand would be to use a counter. Like:

$cc=0;
while(...){ // Whatever your finished condition is
 if($cc==0){
  //INSERT
 }else{
  //UPDATE
 }
 $cc++;
 if($cc==8) $cc=0;
}
zaf
+2  A: 

array_chunk() is the possible answer if I took this question correct.

And then just something like this

foreach ($chunks as $row) {
  array_map $row with mysql_real_escape_string
  implode to get VALUES clause
  INSERT
}

But the real array sample can save a ton of both your own and other people's time

Say, if you want to have saved the keys, not values, array_reverse must be called first.

Col. Shrapnel
+1  A: 
$records = array_chunk($yourArray);

foreach($records as $record)
{
    $record = array_map("mysql_real_escape_string", $record);
    $q = 'INSERT INTO `yourTable` VALUES 
        '.$record[0].', 
        '.$record[1].', 
        '.$record[2].', 
        '.$record[3].', 
        '.$record[4].', 
        '.$record[5].', 
        '.$record[6].', 
        '.$record[7].', 
    ';
    $res = mysql_query($q);
}
Lizard
A: 

I have a PHP 2D array, many keys, each with one value, I need to put this into a MySQL database.

Sounds very odd - PHP doesn't do 2-dimensional arrays. Only nested arrays.

I am aware that the 1st, 9th, 17th, 26th values etc, will need an insert statement

I presume that means that you don't have a 2D array - you've got a 2D data set mapped to a non-nested PHP array....in which case:

for ($x=0; $x<count($data)/8; $x+=8) {
     $qry="INSERT INTO sometable (f1, f2, f3,f4,f5,f6,f7,f8) VALUES (";
     $join='';
     for ($y=0; $y<8; $y++ ) {
       $qry.=$join . prep_val($data[$x+$y]);
       $join=',';
     }
     mysql_query($qry);
}

(where prep_val enloses strings and escapes meta chars)

C.

symcbean
A: 

I think you should keep in the db id of the last inserted row, and how many of the fields in this row are free.

This should allow you to make appropriate update and/or inserts when putting new data into db.

For splitting array into parts you may use array_slice() array_splice() and array_chunk() functions.

Kamil Szot