从数组向数据库插入值

时间:2013-02-27 04:59:59

标签: php mysql arrays

我有一个包含100个值的数组。我想将前10个值插入数据库表的第一行,即。前10个值(col1,col2,...col10)表示db表中的10列。我想将下一个10(11-20)插入第二行。那么如何迭代那个特定的数组呢?

  

我使用了if子句,如if($ key%10 == 0)

3 个答案:

答案 0 :(得分:6)

$my_array = array('a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b',);

$splited_array = array_chunk($my_array, 10);

foreach ($splited_array as $new_array) {

  print_r($new_array);
  // insert a new row with value of $new_array
}

答案 1 :(得分:0)

试试这个:

$res    = array();
$row    = 0;
for($i=0;$i<count($array);$i++){
   if($i % 10 == 0 && $i != 0){
      $row++;
   }
   $res[$row][]  = $array[$i];
}

echo "<pre>";
print_r($res);

foreach($res as $val){
    $col1   = $val[0];
    $col2   = $val[1];
    ..... //// so on
    $col10   = $val[9];

    Insert into databse
}

答案 2 :(得分:0)

//I assume you get this by magic
$inarray = array(...)

//create your command and specify your bound parameters
$stmt = $dbh->prepare("INSERT INTO table (c1, c2, cn..., c10) VALUES (:c1, :c2, ..., :c10)");
$stmt->bindParam(':c1', $c1);
$stmt->bindParam(':c2', $c2);
//...
$stmt->bindParam(':c10', $c10);

//loop over the array, hopping ten items at a time
for ($i = 0; $i < 100; $i += 10)
{
    // update the value of the bound parameter
    $c1 = $inarray[$i + 0];
    $c2 = $inarray[$i + 1];
    //...
    $c10 = $inarray[$i + 9];
    //execute the insert
    $stmt->execute();
}