2015-04-03 103 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