Insert a form with while

Asked

Viewed 216 times

0

ola i have this form that multiplies according to the app registration for the user,

inserir a descrição da imagem aqui

.

see the result graphically,

inserir a descrição da imagem aqui

how do I enter into the database where I can have a user with up to 7 distinct record or more? I am currently doing half q manual but with records q was not to be inserted

session_start();
if (!isset($_SESSION['login']) || $_SESSION['nivel_acesso_id'] != '2') { //verifica se existe um usuario logado.
    
}
$conn = new mysqli("localhost", "root", "", "teste"); 

$brf1 = $_POST['brf1'];
$brf2 = $_POST['brf2'];
$brf3 = $_POST['brf3'];
$brf4 = $_POST['brf4'];
$brf5 = $_POST['brf5'];
$brf6 = $_POST['brf6'];
$brf7 = $_POST['brf7'];

$app1 = '1';
$app2 = '2';
$app3 = '3';
$app4 = '4';
$app5 = '5';
$app6 = '6';
$app7 = '7';
$iduser = $_SESSION['id'];



// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}


$sql = "INSERT INTO events (id_nome, brfinal, aplicativo)
VALUES ('$iduser', '$brf1', '$app1');";
$sql .= "INSERT INTO events (id_nome, brfinal, aplicativo)
VALUES ('$iduser', '$brf2', '$app2');";
$sql .= "INSERT INTO events (id_nome, brfinal, aplicativo)
VALUES ('$iduser', '$brf3', '$app3')";
$sql .= "INSERT INTO events (id_nome, brfinal, aplicativo)
VALUES ('$iduser', '$brf4', '$app4')";
$sql .= "INSERT INTO events (id_nome, brfinal, aplicativo)
VALUES ('$iduser', '$brf5', '$app5')";
$sql .= "INSERT INTO events (id_nome, brfinal, aplicativo)
VALUES ('$iduser', '$brf6', '$app6')";

if ($conn->multi_query($sql) === TRUE) {
    echo "<script>alert('Preencha todos os campos para logar-s333e.'); history.back();</script>";
    header("Location: calendar.php");
} else {
    echo "<script>alert('Preencha todos os campos para logar-s111e.'); history.back();</script>" . $conn->error;
}

$conn->close();

?> 

  • Passes a JSON containing arrays containing data from <forms>.

  • First of all, avoid using images for codes, because if we’re going to do something to help, we’re not going to type what you could have typed here for us. Second I need to know how you send the data to PHP, through the standard Submit <form> or using JS?

  • ok sorry but everything for me here is new but with respect to Submit is the form pattern

3 answers

1

Good morning man, what you can do is the following. First on your FORM you will put at the end of each name of inputs a [] so that it becomes a kind of array when you send the data to PHP. With this, you no longer need to identify the ID of each line as you are doing. On the part of PHP, it is very simple what you will do, basically you will run a INSERT within a foreach or a for where you will pass by parameter the amount of idVoce had in FORM as many times as it will have to run the INSERT in the Bank. It will look like this:

Your input’s where I just copied the DIV with the ones inside, just change the name of these in your HTML:

    <div class="com-sm-4">
        <input type="text" name="app[]">
    </div>

    <div class="col-sm-4">
        <input type="text" name="brinicial[]">
    </div>

    <div class="form-group">
        <input type="text" name="count[]">
        <input type="text" name="brf[]">
    </div>

    <div class="form-group">
        <input type="checkbox" name="naojogou[]">
    </div>

Your script in PHP:

<?php
$id = $connect->insert_id; 
$qtd_insert = sizeof($_POST['app']);

for($i = 0; $i <$qtd_insert; $i++) {
    $app = $_POST['app'][$i];
    $count = $_POST['count'][$i];
    $brf = $_POST['brf'][$i];
    $checkbox = isset($_POST['naojogou'][$i]);

    $query = "INSERT INTO events(id_nome, brfinal, aplicativo) VALUES ('$id', '$brf', '$app')";
    if(!$connect->query($query) === true) {
        die("Erro na inserção dos dados: " . $query . "<br>" . $connect->error)
    }
}
?>

However, since I didn’t have your HTML, I was a little confused about which fields you are inserting in the BD, if not these that I put in the query, just replace them with the other variables there. In the case of the checkbox, you can check whether a checkbox is checked by isset, it makes a kind of check where if the checkbox is marked, it exists, otherwise it does not exist, and with that it can take or not the value of the same.

  • thank you very much but the only fields q goes to db are the app and brf and the user id testing with the example q gave and thank you very much for everything.

  • If the answer satisfies your question, don’t forget to mark as " Correct " and mark a point by clicking the up arrow rs.

  • good afternoon I made the changes only it inserts only the of the 1º imput o of the repetition it does not show however when I give a print_r of brf[] it shows Array ( [0] => 50 [1] => 120 ). remembering that I just want to insert in the database the values of brf the user id and the app q it is registered

0


Guys I managed to solve the problem after a while analyzing here a thank you so much for everything you’ve done for me.

the way I was able to solve was by changing the input of the app form taking out the disabled that does not pass value and putting the readonly that blocks the same way and passes values the other was changing the $Row['idnome'] who passed only the name and not the id the rest was what Leo went through as example.

label for="inputEmail3" class="col-sm-2 control-label">Aplicativo</label>
                      <div class="col-sm-4">
                      <?php echo $row['idnome'];?>
                          <input type="hidden" class="form-control" name="app[]" id="app"  value="<?php echo $row['idapp'];?>" readonly>

                      </div>

and php was like this

include_once("conexao.php");

$qtd_insert = count($_POST['brf']);


for($i = 0; $i <$qtd_insert; $i++) {
    $app = $_POST['app'][$i];
    $brf = $_POST['brf'][$i];
    
    

   $query = "INSERT INTO events(id_nome, brfinal, aplicativo) VALUES ('".$_SESSION['id']."', '$brf', '$app')";
    if(!$conn->query($query) === true) {
     die("<script>alert('Erro na inserção dos dados!!!');</script>: " . $query . "<br>" . $conn->error);
     
    }

0

You need to understand the operation of receiving data from the forms by PHP, when it comes to forms with repeated information as is your case, you have another option to facilitate the processing of this data that would look like this:

while($row=mysqli_fetch_assoc($result)){
    <input type="text" name="nome_do_input_1[]">
    <input type="text" name="nome_do_input_2[]">
}

Note: Note that this is an example of how you can do by adding your code and values as you wish, as long as the name of the <input> is accompanied by [], for so the PHP will understand that this input is a array.

In the PHP you will receive a array thus:

array (size=3)
  'nome_do_input_1' => 
    array (size=2)
      0 => string 'input 1' (length=7)
      1 => string 'input 1 de novo' (length=15)
  'nome_do_input_2' => 
    array (size=2)
      0 => string 'input 2' (length=7)
      1 => string 'input 2 de novo' (length=15)

So just treat the data as arrays that are using repeat loops to make the input treatments, remembering that each numerical key of the arrays are respectively of each app, example: every key 0 is of the first app, all-key 1 is from the second, etc.

  • good afternoon Wees like me have very little knowledge I do not know how to insert in DB the brf[] array that with print_r($_POST) shows this result Array ( [Count] => 2 [brf] => Array ( [0] => 50 q refers to the 1st form [1] => 120 which refers to the 2nd form and depending on the USER it can have up to 10 or more form) ) a a os app são traz no DB onde estão cadastrado aqle USER a poder jogar com o exemplo do leo.

Browser other questions tagged

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