How to create records in the MYSQL table according to the value of the $nregistros PHP variable

Asked

Viewed 46 times

2

I have a $nregistros variable that defines the value of records to be inserted in the table "Formularios".

If $nregistros is equal to 4 for example, it should insert 4 rows as follows:

formularios
id|campo
6 | 1
7 | 2
8 | 3
9 | 4

the "id" field is autoindex, and the "field" field should start at 1 and go to the final value of $nregistros, in this case, 4

How can I do that?

1 answer

2


For this feat, a simple for can solve.

Try something like :

<?php
    $nregistros = 4;
    for($n = 1; $n <= $nregistros; $n++) {       
        echo "INSERT INTO formularios SET campo = $n; ";
    }
?>

In place of echo enter your insertion query into the database.

Thus, I obtained the following output:

INSERT INTO formularios SET campo = 1; INSERT INTO formularios SET campo = 2; INSERT INTO formularios SET campo = 3; INSERT INTO formularios SET campo = 4;

Remember that if the number is in the variable $nregistros is too long, there will be loss of performance, by the fact of the realization multi-purpose insert.

  • Just what I needed, thanks!

  • I’m glad I could help. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.