Skip to content
Advertisement

How to use a for loop to insert multiple records in a database table

I have simplified my problem into the following code:

$sql_abc = "CREATE TABLE $tbl_abc(
    x INTEGER(255)
)
";

echo "About to execute $sql_abc";
if (mysqli_query($conn, $sql_abc)) {
    echo "Table $sql_abccreated successfully<br>";
} else {
    echo "Error creating table: " . mysqli_error($conn) . "<br>";
}

for ($x = 1; $x <= 10; $x++) {
    $sql_abc = "INSERT INTO $tbl_abc VALUES ($x)";
}

if (mysqli_query($conn, $sql_abc)) {
        echo "New records created successfully<br>";
    } else {
        echo "Error: " . $sql_abc. "<br>" . mysqli_error($conn);
    }

I am trying to get 10 records in the table, with each incrementing by one in the ‘x’ field.

However, all I see is:

Here is what I see

Please advise. Thank you.

Advertisement

Answer

Here is how you can do that.

for ($x = 1; $x <= 10; $x++) {
    
    $sql_abc = "INSERT INTO $tbl_abc VALUES ($x)";

    //this query will execute for each value of $x
    mysqli_query($conn, $sql_abc);
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement