2014-02-27 84 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); 
}