Insert into multiple input fields in different tables

Asked

Viewed 566 times

7

I have the date fields, CNPJ, latitude, longitude, site, facebook, on the same screen, only are 3 different tables, how do I give the insert in them from the same button?? What do I use to save the information but not all fields are required.

  • 3

    In your PHP script you have to make 3 queries of Insert to write the data. Post your PHP code and the structure of your 3 tables so we can help you better.

  • The question is a bit incomplete. What button are you talking about? "Insert" where? SQL? Are you using PDO, mysqli or mysql? And what is your question regarding entering something into a database table, then?

2 answers

0

Hello, all right?

You can use input arrays in html by separating by each table you want to insert the data, for example:

    <form action="inputArray.php" method="post">

        <label>tbl1 Nome</label>                
        <input type="text" name="tbl1[nome]"/><br/>
        <label>tbl1 Sobrenome</label>
        <input type="text" name="tbl1[sobrenome]"/><br/>
        <label>tbl1 Idade</label>
        <input type="text" name="tbl1[idade]"/><br/><br/>

        <label>tbl2 Nome</label>
        <input type="text" name="tbl2[nome]"/><br/>
        <label>tbl2 Sobrenome</label>
        <input type="text" name="tbl2[sobrenome]"/><br/>
        <label>tbl2 Idade</label>
        <input type="text" name="tbl2[idade]"/><br/>
        <input type="submit" value="Enviar"/>
    </form>

If on the destination page you give a print_r($_POST), will have the following result:

Array ( 
[tbl1] => Array ( [nome] => [sobrenome] => [idade] => )
[tbl2] => Array ( [nome] => [sobrenome] => [idade] => ) 
)

where tbl1 and tbl2 are your tables, after that is only do the Inserts

$tbl1 = $_POST['tbl1'];
$sql = "INSERT INTO tbl1 (nome, sobrenome, idade) VALUES($tbl1['nome'], $tbl1['sobrenome'], $tbl1['idade'])";`

and then just repeat to the other tables.

I hope I helped. I’m available for any questions. Hug.

0

I understood that all fields are in a single FORM, and that you send them all in the same request for processing/writing in different tables. You can separate the data passed by the form and create independent SQL queries to record them. Assuming the script receives the data via $_POST:

´foreach($_POST as $var => $value){
  if($var == 'cnpj'){
   $query = "INSERT INTO table_name1($var) VALUES ($value); ";
  }
  if($var == 'latitude'){
   $query = $query . "INSERT INTO table_name2($var) VALUES ($value); ";
  }}
  echo $query;´

The answer should be this one:

´INSERT INTO table_name1(cnpj) VALUES (000000000000); 
 INSERT INTO table_name2(latitude) VALUES (1245165421341);´

In the end, just run the $query graduate.

Browser other questions tagged

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