2014-02-27 44 views
-1

我在我的脚本中,我想通过关联数组循环后将数据插入到我的数据库中的点。如何循环通过多维关联数组正确的方式

该代码工作到目前为止,但由于我是编程新手,我希望知道是否有更有效的替代方法来做我正在做的事情,因为我将在数组增长时添加更多的elseif,还有事实上,我每次迭代后都要查询我的数据库。

foreach($database as $key=>$value) { 

foreach($value as $field => $cell){ 

    if ($field =='itemid') { 
     echo "the item id is $cell"; 
     $col1 = $cell ; 
    } 
    elseif ($field =='title') { 

     echo "the title is $cell"; 
     $col2 = $cell; 
    } 
    elseif ($field =='starttime') { 

     echo "the start time is $cell"; 
     $col3 = $cell; 
    } 

} 
$query = "INSERT INTO cordless_drill(itemid,title,starttime) VALUES ('$col1','$col2','$col3')"; 
mysqli_query($dbc,$query); 

} 
+0

也许你应该只映射它并将其标记为文字越好。所以你可以很容易地追踪'key:values' – Jhn

回答

0
// here is a code snippet 

// $db = new MyDbClass(); 

// $db->insert->('cordless_drill', $cell); // where $cell is holding key/value pairs 

public function insert($table, $obj) { 
    return $this->query("INSERT INTO ".$table.$this->obj2KeyValue($obj)); 
} 

private function obj2KeyValue($obj) { 
    $i = count($obj); 
    $k = ""; $v = "";  
    $init = false; 
    $sql = " SET "; 
    while (list($k, $v) = each($obj)) { 
     if ($v != "") { 
      $v = $this->mysqli->real_escape_string($v); 
      if ($init) $sql .= ", "; 
      else $init = true; 
      $sql .= $k.'="'.$v.'"'; 
     } 
    } 
    return $sql; 

} 


public function query($q) { 
    if ($this->debug) { 
     $logFile = "sql_query.log"; 
     $handle = fopen($logFile, "a+"); 
     $data = $q."\n"; 
     fwrite($handle, $data); 
     fclose($handle); 
    }  
    return $this->mysqli->query($q); 
}