简体   繁体   English

php只将最后一个数组记录插入到sql中

[英]php inserts only last array record into sql

I have working code, which inserts data into csv file.我有工作代码,它将数据插入到 csv 文件中。 Here is a part of it:这是其中的一部分:

if (isset($_POST['array'])) {
        foreach ($_POST['array'] as $loop) {
            $txt = $txt . $loop['name'] . ";" . $loop['email'];
            $txt .="\n";
        }
    }

Instead of csv, i would like it to insert data into mysql database, so i have simply changed the code to:我希望将数据插入 mysql 数据库而不是 csv,所以我只是将代码更改为:

    if (isset($_POST['array'])) {
        foreach ($_POST['array'] as $loop) {

            $sql = "insert into persons (Name, Email)
                    values ('" . $loop['name'] . "', '" . $loop['email'] . "')";     
        }
    }

Only the last record is saved into the persons table.只有最后一条记录被保存到人表中。 There are no errors, but all the previous records except last are not inserted.没有错误,但没有插入除最后一个之外的所有先前记录。 Why?为什么?

Better way is only one time create insert更好的方法是一次创建insert

if (isset($_POST['array'])) {
    $values = [];
    $sql = "insert into persons (Name, Email) values ";

    foreach ($_POST['array'] as $loop) {
        $values[] = "('" . $conn->real_escape_string($loop['name']) . "', '" . $conn->real_escape_string($loop['email']) . "')";     
    }

    if (!empty($values)) {
        $conn->query($sql . implode(', ', $values));
    }
}

The reason why it doesn't work is because you never execute your SQL query anywhere.它不起作用的原因是因为您从未在任何地方执行 SQL 查询。

To execute the query you should first prepare the statement and then bind the params and execute.要执行查询,您应该首先准备语句,然后绑定参数并执行。

// Your connection to DB
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli('localhost', 'username', 'password', 'dbname');
$mysqli->set_charset('utf8mb4'); // always set the charset


if (isset($_POST['array'])) {
    $stmt = $mysqli->prepare('INSERT INTO persons (Name, Email) VALUES (?,?)');
    foreach ($_POST['array'] as $loop) {
        $stmt->bind_param('ss', $loop['name'], $loop['email']);
        $stmt->execute();
    }
}

Please execute query inside the loop as given below请在循环内执行查询,如下所示

...
$conn = mysqli_connect($servername, $username, $password, $dbname);
...

if (isset($_POST['array'])) {
    foreach ($_POST['array'] as $loop) {

        $sql = "insert into persons (Name, Email)
                values ('" . $loop['name'] . "', '" . $loop['email'] . "')";    
        $conn->query($sql);// Query should execute inside loop       

    }
}

I had the same issue inserting JSON arrays into MySQL and fixed it by putting the mysqli_stmt->execute() function inside the foreach我在将 JSON 数组插入 MySQL 时遇到了同样的问题,并通过将mysqli_stmt->execute()函数放在foreach修复它

// loop through the array
foreach ($data as $row) {
    echo "Data has been Uploaded successfully <br>";
    // get the project details
    $id = $row['id'];
    $name = $row['name'];
    $togglCid = $row['cid'];
    // execute insert query
    mysqli_stmt_execute($sql);
}

This means it executes the code after each loop这意味着它在每次循环后执行代码

If you want to execute the query outside the loop Try using as following如果你想在循环外执行查询尝试使用如下

 if (isset($_POST['array'])) {
            $sql="";
            foreach ($_POST['array'] as $loop) {

                $sql .= "insert into persons (Name, Email)
                        values ('" . $loop['name'] . "', '" . $loop['email'] . "');\n";     
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM