2015-04-03 105 views
1

我有這個多維數組插入到mysql數據庫:插入多維數組MySQL表

Array ( 
[0] => Array 
     ([0] => Mechanics of Solids [1] => 257 [2] => Civil Engineering 
     [3] => CEN [4] => Golam Kibria uddin [5] => 02-APR-2015 [6] => 
     1:30am [7] => Md. Tushar Ahmed [8] => present) 

[1] => Array 
     ([0] => Mechanics of Solids [1] => 257 [2] => Civil Engineering 
     [3] => CEN [4] => Golam Kibria uddin [5] => 02-APR-2015 [6] => 
     1:30am [7] => Mrs. Monira Akter [8] => absent) 
[2] => Array 
     ([0] => Mechanics of Solids [1] => 257 [2] => Civil Engineering 
     [3] => CEN [4] => Golam Kibria uddin [5] => 02-APR-2015 [6] => 
     1:30am [7] => JOYNAB AKTER [8] => leave) 
[3] => Array 
     ([0] => Mechanics of Solids [1] => 257 [2] => Civil Engineering 
     [3] => CEN [4] => Golam Kibria uddin [5] => 02-APR-2015 [6] => 
     1:30am [7] => BEAUTY AKTER [8] => leave) 
[4] => Array 
     ([0] => Mechanics of Solids [1] => 257 [2] => Civil Engineering 
     [3] => CEN [4] => Golam Kibria uddin [5] => 02-APR-2015 [6] => 
     1:30am [7] => PURABI BARUA [8] => absent) 
[5] => Array 
     ([0] => Mechanics of Solids [1] => 257 [2] => Civil Engineering 
     [3] => CEN [4] => Golam Kibria uddin [5] => 02-APR-2015 [6] => 
     1:30am [7] => SETU BISWAS [8] => present) 
) 

我的表名爲「student_attendance」和列:

'att_id', //it's automatically incremented. 
    'subject_name' , 'subject_code', 'department_short_name', 
    'department_name', 'teacher_name', 'date', 'time', 'student_name', 
    'att_status' 

請幫助我把這個數組插入到這個mysql表中。這應該由foreach循環完成。

+0

你嘗試過什麼來實現它,或只是發佈了一個問題 – 2015-04-03 06:30:23

+0

我試圖.... – 2015-04-03 08:06:03

回答

1

自已經分批,只是採用簡單的foreach循環。我建議用PDO準備語句:

$db = new PDO('mysql:host=localhost;dbname=database_name', 'username', 'password'); 
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

$insert = $db->prepare(
    'INSERT INTO table_name (subject_name , subject_code, department_short_name, 
    department_name, teacher_name, date, time, student_name, att_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'); 
); 

foreach($your_array as $values) { 
    $insert->execute($values); 
} 
+0

完美的工作。非常感謝。 – 2015-04-03 08:27:44

+0

@BorhanNirob很高興這有幫助 – Ghost 2015-04-03 10:27:53

0
$sql="insert into student_attendence(att_id,subject_name,subject_code,department_short_name,department_name,teacher_name,date,time,student_name,att_status) values"; 

$items_sql = array(); 
    if (count($items)) { 
     foreach ($items as $item) { 
      $items_sql[] = "('', '{$item[0]}','{$item[1]}','{$item[2]}'....... and so on)"; 
     } 
    } 

    $sql .= implode(", ", $items_sql); 

試試這個...其中$項目將成爲您的變量中,多維數組來了...

+0

請清除我約$項目變量。我想你的答案會很有幫助。 – 2015-04-03 06:42:46

+0

剛編輯我的答案..檢查它是否有任何查詢,然後讓我知道 – 2015-04-03 06:44:39