将字符串和数组的组合插入MYSQL

问题描述 投票:1回答:1

我在这里找到了类似的问题,但对我的情况来说没什么。我需要从一组数组和重复字符串的值组合中为数据库创建多个条目。举个例子:

$sql = "INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time)
VALUES ('$venue', '$date', '1', '$info', '$title', '$repertoire_formatted', $time)";

$venue$time,和$date是阵列。应将'1'添加到数据库的EACH条目而不做任何更改。 $info$title和AND$repertoire_formatted是对于数据库的每个条目应该重复的字符串,即插入而没有任何变化。

因此,以下示例显示了每个变量的内容:

$venue = array('venue1', 'venue7', 'venue50');
$date = array('2019-01-01', '2019-02-02', '2019-03-03');
$time = array('20:00:00', '19:00:00', '18:00:00');
$info = 'General info about this event';
$repertoire_formatted = 'Music that people will play at this event';

我的SQL数据库设置为为每个输入变量获取不同类型的数据。

这是我的代码(不工作):

session_start();
$_SESSION["servername"] = "localhost";
$_SESSION["username"] = "sonch_nB";
$_SESSION["password"] = 'hello';
$_SESSION["dbname"] = "sonch_MAIN";
date_default_timezone_set('Europe/Zurich');


$venue = ($_POST['venue']);
$date = ($_POST['date']);
$ensemble_id = '1'; //THIS WILL BE SET VIA LOGIN
$info = ($_POST['info']);
$title = ($_POST['title']);
//FORMAT INCOMING VARS CODE SKIPPED//

// Create connection
    $conn = new mysqli($_SESSION['servername'], $_SESSION['username'], $_SESSION['password'], $_SESSION['dbname']);
// Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
        } 

//NEED TO LOOP INPUT TO MYSQL NUMBER OF VALUES IN ARRAY
$stmt = $conn->prepare("INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time) VALUES (?, ?, '1', ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $v, $d, $info, $title, $repertoire_formatted, $t);
for ($i = 0; $i < count($venue); $i++) {
    $v = $venue[$i];
    $d = $date[$i];
    $t = $time[$i];
    $stmt->execute();
}

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$stmt->close();
php mysql
1个回答
1
投票

你应该使用准备好的声明。在MySQLi中(假设您的连接是$conn):

$stmt = $conn->prepare("INSERT INTO sonch_MAIN.Concert (venue_id, date, ensemble_id, info, title, repertoire, time)
VALUES (?, ?, '1', ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $v, $d, $info, $title, $repertoire_formatted, $t);
for ($i = 0; $i < count($venue); $i++) {
    $v = $venue[$i];
    $d = $date[$i];
    $t = $time[$i];
    if ($stmt->execute() === TRUE) {
        echo "New record created successfully";
    } else {
         echo "Error: " . $conn->error;
    }
}
$stmt->close();
© www.soinside.com 2019 - 2024. All rights reserved.