2014-09-19 58 views
0

我想將一個數組($array)插入Mysql表(notification),我試過但沒有輸入。我該如何解決這個問題?如何將數組插入到Mysql表中

$select = "SELECT * FROM addclique WHERE adder_id = :session_id"; 
$param1 = array ('session_id' => $_SESSION['id']); 
$cliques = $db->query($select, $param1); 

foreach($cliques as $key) 
{ 
     $array[] = $key['clique_id'];   
} 
$array[] = $key['clique_id']; 
$notijfy = new Notification(); 
$notijfy->addCircle($array); 

function addCircle($id_involve){ 
    $escaped_values = array_map('mysql_real_escape_string', array_values($array)); 

    $sql2 = "INSERT INTO notification(id_involve) VALUES (:id_involve)"; 
    $param2 = array ('id_involve' => implode(", ", $escaped_values)); 
    $result2 = $this->db->query ($sql2, $param2); 
} 
+0

的http:// stackoverfl ow.com/questions/13507496/pdo-php-insert-into-db-from-an-associative-array – 2014-09-19 23:28:56

回答

0

有幾種方法。 我只想做一些簡單的像這樣:

foreach($cliques as $key){ 

     $array[] = $key['clique_id']; 

} 

$notijfy = new Notification();  
$notijfy->addCircle($array);  
function addCircle($array){ 
$insert_string = ''; 

$count = 0; 
foreach ($array as $k => $v){ 

$count++; 


${$k} = mysqli_real_escape_string($this->db, $v); 

$insert_string .= "(" . ${$k} . ")"; 

if ($count < sizeof($array)){ 

$insert_string .= ","; 

} 

     } 
$sql2 = "INSERT INTO notification(id_involve) VALUES $insert_string;"; 

$result2= $this->db->query ($sql2, $param2); 

} 

你的主要錯誤是,你試圖通過($調用函數時傳遞一個陣列,但在函數本身的參數被列爲$ id_involve,當你顯然需要一個你在函數本身中使用的$ array變量的時候,我也不明白你爲什麼要在一開始就在foreach循環之外添加一個元素到$ array變量中。 。

而不是$this->db只需使用你的連接變量

+0

不要忘記在發佈之前先格式化你的代碼':-)' – halfer 2014-09-19 23:52:13