1

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.

5
  • you need to put the actual insert statement in the for loop, so each time it increments the $x it should also execute the insert statement as well, right now the loop completes it's iterations and the insert statement only executes for the last value of $x because your insert statement is after the for loop Commented Dec 14, 2020 at 4:20
  • Could you please suggest an edit to the code to fix it? Is $sql_abc = "INSERT INTO $tbl_abc VALUES ($x)"; not currently in the for ($x = 1; $x <= 10; $x++) loop? Thank you! Commented Dec 14, 2020 at 4:23
  • please share complete code so I can fix it for you. Show where you execute the "INSERT INTO $tbl_abc VALUES ($x)" query string ? Commented Dec 14, 2020 at 4:26
  • Done, I've added it to the post. Thank you. Commented Dec 14, 2020 at 4:29
  • 1
    A good practice will be to handle connection error only once when you first make the db connection, you don't need to check the connection every time you execute a query. Commented Dec 14, 2020 at 4:38

1 Answer 1

2

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

2 Comments

Thank you so much. I'm only starting out with php now and am unfamiliar with how to execute the queries!
No worries, Just search about the best way to handle db connections and learn best coding practices. Have a good day.

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.