php数组到mysql表中的列行

weylhg0b  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(241)

我有一个叫奥尔马利的数组

$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表中的列行

mwkjh3gx

mwkjh3gx1#

有很多方法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();
n3ipq98p

n3ipq98p2#

你必须在数组中循环并逐个插入。

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

相关问题