Dram
Dram

Reputation: 31

Database Error when insert data with loop

I want to insert data in database with dynamic php variable and when I check the script in database I have only one record :(

$low_0 = 0;
$low_1 = 1;
$low_2 = 2;
$nr = 9;

for ($i = 0; $i < $nr; $i++) {
    $sql = 'INSERT INTO prognoza_curenta (ora, prognoza, min, max, reg_date)
            VALUES (' . "${'low_' . $i}, " . "11," . "22," . "33," . "'$timp')";
    echo "$sql" . "<br>";
}

if (mysqli_query($db, $sql)) {
    echo 'Data send' . "<br>";
} else {
    echo 'Error send.' . mysqli_error($sql) . "<br>";
}

Upvotes: 0

Views: 73

Answers (2)

Murad Hasan
Murad Hasan

Reputation: 9583

The Solution With prepared Statement:

$stmt = $conn->prepare("INSERT INTO prognoza_curenta (ora, prognoza, min, max, reg_date) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $ora, $prognoza, $min, $max, $reg_date);

// set parameters and execute
for ($i = 0; $i < $nr; $i++) {
    $ora= ${'low_' . $i};
    $prognoza= "11";
    $min= '22';
    $max = '33';
    $reg_date = $timp;
    $stmt->execute();
}

As Suggested by @MarkBaker, This is procedure of prepare statement. Please let me know.

Upvotes: 1

Matt
Matt

Reputation: 1757

Change your loop to this:

$sql = 'INSERT INTO prognoza_curenta (ora, prognoza, min, max, reg_date)  VALUES';
for ($i = 0; $i < $nr; $i++) {
    $sql .= ' (' . "${'low_' . $i}, " . "11," . "22," . "33," . "'$timp')";
}

Upvotes: 1

Related Questions