0

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>";
}
4
  • 2
    you miss to run mysqli_query inside loop. Also you can concatenate the $sql and only one time. $sql .= 'INSERT....'; Commented May 8, 2016 at 12:53
  • 1
    Start by learning to use prepared statements with bind variables in your SQL queries, ad then you wouldn't need to worry about horribly mangling your strings in this way Commented May 8, 2016 at 12:53
  • You are overwriting $sql and only the last loop remains for when you insert it. Commented May 8, 2016 at 12:53
  • Thx for all tips it's working now. Commented May 8, 2016 at 12:59

2 Answers 2

1

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')";
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.