How to make this insertion dynamically?

Asked

Viewed 157 times

-2

How to do this insertion dynamically knowing the total number of columns?

mysql_query("INSERT INTO VOT_PART_MUN_ZONA VALUES ( 

   '$dados[0]',
   '$dados[1]',
   '$dados[2]',
   '$dados[4]',
   '$dados[...]',
   '$dados[19]'

)");
  • You need to give more details, from the columns. In theory the number of values should be the same as columns.

  • 2

    This does not seem like a good idea. It is good to specify the fields where you are inserted. So it’s easy for another person who will tamper with your code in the future to understand what is being done there.

  • 1

    I agree with @Wallacemaxters better specify what you are sending and where than then hit yourself in the future to know what is coming/going;

  • What I mean is assuming that the number of columns is exactly the amount of data entered, how to insert this data that is in a text file without repeating all the items in this array !!! No one will touch the code but if I have for example $data[500] imagine specifying 1 by 1 !!!!

  • A table with 500 columns? I find it difficult. And, if it exists, it was poorly structured. To know this, you have to count the number of columns. Unless you want to wear one '"' . implode('","', $dados) . '"' to do this. But I would say: That would be a lady gambiarra. sprintf('INSERT INTO tabela VALUES("%s")', implode('","', $dados))

  • It would be something like this? INSERT INTO 'usuarios' ('id', 'nome', 'email') VALUES (NULL, 'Thiago', '[email protected]'), (NULL, 'Fulano da Silva', '[email protected]'), (NULL, 'Ciclano', '[email protected]') Source: http://blog.thiagobelem.net/cadastrando-multiplos-registros-no-mysql-ao-mesmo-tempo/

  • The guy would have to reorder the array if the table field was changed from position :(

Show 2 more comments

1 answer

0

Although it is not a recommended practice, you can do it as follows.

Suppose your array has 500 data, such as those generated by the function below range.

We could use the function implode to bring all the values.

$dados = range(1, 500);


$insert = sprintf('INSERT INTO tabela VALUES("%s")', implode('","', $dados));


echo $insert;

http://ideone.com/BV4Byu

The recommendation would be you inform the fields where you will enter this data. One of the benefits that can be cited is the facilitation of reading the code, whoever was editing it.

Browser other questions tagged

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