将多维php数组插入mysqli数据库

时间:2017-01-04 08:39:16

标签: php mysql arrays mysqli

这里的代码不起作用

$sub1="Mathematics";
$sub2="Chemistry";
$sub3="Biology";
$sub4="Hindi";
$sub5="History";
$sub6="Malayalam";
$sub7="Physics";

$timetable = array
  (
  array("Monday","Tuesday","Wednesday","ThursdaY","Friday"),
  array($sub1,$sub1,$sub1,$sub1,$sub1),
  array($sub3,$sub2,$sub6,"Arts",$sub5),
  array($sub2,"Ethics","science",$sub3,"science"),
  array($sub4,$sub3,$sub5,$sub7,$sub3),
  array("Arts",$sub6,$sub5,$sub2,$sub7),
  array($sub6,$sub2,$sub4,$sub6,$sub5),
  array($sub5,$sub4,$sub3,$sub4,$sub6)
);
 for($i=$q;$i<=7+$q;$i++)
    {
     $query = "INSERT INTO `class`(`class`, `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`) VALUES ('$class','$array[$i][0]', '$array[$i][1]', '$array[$i][2]', '$array[$i][3]', '$array[$i][4]', '1')";

           $que=mysqli_query($obj->conn,$query);  
}

我想将它插入到一个mysqli表中,其中主题数组的周(sub1,sub2,sub3,sub4,sub5)是列标题,每个后续数组是表中的一行。

任何人都可以建议最好的方法来做到这一点,因为我撞墙了,它给我留下了一个伤脑筋!

2 个答案:

答案 0 :(得分:0)

$i = 1;    
for($timetable as $tt) {

    if( $i != 1 ) {

        $query = "INSERT into class (`class`, `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`) VALUES (`$class`, `$tt[0]`, `$tt[1]`, `$tt[2]`, `$tt[3]`, `$tt[4]`, 1)";

        $que = mysqli_query($obj->conn, $query);
    }
    $i = $i + 1;
}

试试这个!希望对你有用。

答案 1 :(得分:0)

我希望您能理解我想对您的代码说些什么。

$sub1="Mathematics";
$sub2="Chemistry";
$sub3="Biology";
$sub4="Hindi";
$sub5="History";
$sub6="Malayalam";
$sub7="Physics";

$class = 'XII';

$timetable = array
  (
  array($sub1,$sub1,$sub1,$sub1,$sub1),
  array($sub3,$sub2,$sub6,"Arts",$sub5),
  array($sub2,"Ethics","science",$sub3,"science"),
  array($sub4,$sub3,$sub5,$sub7,$sub3),
  array("Arts",$sub6,$sub5,$sub2,$sub7),
  array($sub6,$sub2,$sub4,$sub6,$sub5),
  array($sub5,$sub4,$sub3,$sub4,$sub6)
);

 for($i=0;$i<=7;$i++) {
     $query = "INSERT INTO `class`(`class`, `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`) VALUES ($class,$timetable[$i][0], $timetable[$i][1], $timetable[$i][2], $timetable[$i][3], $timetable[$i][4],1)";

           $que=mysqli_query($obj->conn,$query);  
}

我在这里有一些假设,例如$class = 'XII'"class"表有7个字段'class', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday',其中'saturday'似乎是假日或者其他东西,因为它总是得到1。 / p>

或者替代你cna考虑使用foreach

 foreach($timetable as $ttable){
         $query = "INSERT INTO `class`(`class`, `monday`, `tuesday`, `wednesday`, `thursday`, `friday`, `saturday`) VALUES ($class,$ttable[0], $ttable[1], $ttable[2], $ttable[3], $ttable[4],1)";

         $que=mysqli_query($obj->conn,$query);  
  }

如果每次为它插入1时,为什么你在$ timetable的第3个子数组中有第5个元素,我也不明白。