如何在具有键值对数据数组的表中一次插入多行

时间:2017-09-24 06:04:46

标签: php mysql sql arrays sql-insert

我想将array() key value对数据插入表格

<?php
$foreignKey = 2;
$array = array(
   'availability' => array(
       array('day' => 'monday','time' => 'am'),
       array('day' => 'wednesday','time' => 'pm'),    
   ),
);

我的可用性表 - 开头

表:可用性

| id  |  foreign_id  |   day  |  time  |
+-----+--------------+--------+--------+

结果表:

| id  |  foreign_id  |   day    |  time  |
+-----+--------------+----------+--------+
|  1  |       2      | monday   |  am    |
+-----+--------------+----------+--------+
|  2  |       2      |wednesday |  pm    |
+-----+--------------+----------+--------+


$sql = "INSERT INTO availability ";

2 个答案:

答案 0 :(得分:2)

您可以遍历数组并绑定并执行

$stmt->prepare("INSERT INTO availability (fld1, fld2) VALUES(?, ?)");
foreach($array as $row)
{
    $stmt->bind_param($row['fld1'], $row['fld2']);
    $stmt->execute();
}

答案 1 :(得分:0)

$array = array(
     array('day' => 'monday','time' => 'am'),
     array('day' => 'wednesday','time' => 'pm') 
);

foreach($array as $key => $value)
{
    $sql = "INSERT INTO `availability`(`foreign_id`,  `day`,`time`)VALUES($foreignKey, '$value[day]', '$value[time]') ";
}