将多维数组插入mysql表

时间:2015-04-03 06:27:35

标签: php 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循环来完成。

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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);

试试这个......其中$ items将是你的变量,多维数组即将来临......