Skip to content
Advertisement

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?

Advertisement

Answer

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();
    }
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement