如何从数组创建多个mySQL插入?

时间:2016-04-15 19:37:44

标签: php mysql

我有一系列hasha,b,c,d,e的形式,我通过以下内容完成

$hashes = array();
while(($row =  mysql_fetch_assoc($sql))) {
    $hashes[] = $row['hash'];
} 

$_SESSION['hashes'] = implode(',', $hashes); // a,b,c,d,e

我的问题是如何添加如下所示的多个插入?

INSERT INTO alerts_data (alerts_data_id, alerts_data_hash) 
VALUES 
('$last insert id', 'hash 1'),
('$last insert id', 'hash 2')
('$last insert id', 'hash 3')

1 个答案:

答案 0 :(得分:0)

在MySQLi中使用Prepared Statements并循环插入查询以插入多个记录。

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}


// prepare and bind
$stmt->prepare("INSERT INTO alerts_data (alerts_data_id, alerts_data_hash) VALUES (?, ?)");

$hashes = array();
while(($row =  mysql_fetch_assoc($sql))) {
    $hashes[] = $row['hash'];
} 


foreach($hashes as $key => $hashe)
{
    $stmt->bind_param($key, $hashe['hash']);
    $stmt->execute();
}
$stmt->close();
$conn->close();
?>