简体   繁体   中英

php inserts only last array record into sql

I have working code, which inserts data into csv file. 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:

    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

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.

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

// 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";     
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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