PHP数组到MySQL表中的列行

时间:2018-11-14 08:58:55

标签: php mysql

我有一个名为olmali的数组

$olmali = $_POST['result'];

print_r($olmali); 结果如下:

Array ( 
    [0] => 1
    [1] => 1
    [2] => 20
    [3] => 2 
    [4] => 3
    [5] => 5
    [6] => 6 
    [7] => 7 
    [8] => 9 
    [9] => 8 
    [10] => 10
    [11] => 11
    [12] => 13
    [13] => 12 
    [14] => 12
    [15] => 14 
    [16] => 15
    [17] => 16
    [18] => 17
    [19] => 17
    [20] => 19
    [21] => 20
)

结果将要测试phpmyadmin中SQL表中的列,如:

id        test
1         array

但是我希望:

id        test
1          1
2          1
3          20
4          2
5          3
6         ....and goes on

如何解决此问题?有什么办法,我该怎么办。 PHP数组到MySQL表中的列行

2 个答案:

答案 0 :(得分:1)

您必须遍历数组并一一插入。

foreach($olmali as $v)
{
    //insert query goes here
    $sql = "INSERT INTO tbl_name (test) VALUES ('$v')";

   // Then Execute the query 
}

另一种方法是使用Bulk Insert

$sql = "INSERT INTO tbl_name (test) VALUES ";   

foreach($olmali as $v)
{
    //Concatenate values in bulk
    $sql .= "('$v'),";
}

$sql = rtrim($sql, ','); // Remove extra comma at the end
// Then execute query

答案 1 :(得分:0)

有很多方法 1:使用批量插入

$qry = "INSERT INTO tableName(test) VALUES ";
    foreach($olmali as $val){
       $qry .="($val),";
    }

    $qry = preg_replace("/\,$/", ";", $qry);

    $conn->query($sql);

2:使用prepare语句首选方式

$stmt =  $db->stmt_init();
$stmt->prepare("INSERT INTO tableName(test) VALUES(?)");
foreach($olmali as $val)
{
    $stmt->bind_param('i',$val);
    $stmt->execute();
}
$stmt->close();