Insert only filled data from the PHP array

Asked

Viewed 356 times

2

I have a chart, and I made a loop for her to receive input and also to make Insert, however I’m having problems in the INSERT and UPDATE. Where I have two fields codigo_tipo,descricao that are always inserted together in the field codigo_produto, But, a product code can have N types and descriptions as it can have only 1.

So if I fill only the first line, the others are sent in white to the database, as I do so that only filled lines are sent to the bank and they are updated later if I want to change them.

index php.

<form action='salvar.php' method='POST'>
    <?php 
        $sql = "SELECT * FROM tipoprod"; 
        $resulta = $conn->query($sql);
        $row = $resulta->fetch_assoc();
    ?>
    <div class='form-group col-lg-4'>
        <label>  <b>Código do Produto:</b> </label>
        <input type="text" maxlength="6"  name="codigo_produto" value="<?php $row['codigo_produto'] ?>"><br><br>
    </div>

    <table border="2"><!-- Iniciando a Tabela -->

        <thead>
            <tr><!-- Início dos Títulos da Tabela / Cabeçalho -->
                <th>Código</th>
                <th>Descrição</th>                                                                                                              
            </tr><!-- Fim dos Títulos da Tabela / Cabeçalho -->
        </thead>

        <tbody>
        <?php
            include("conn.php");

            for($i = 1; $i <= 5; $i++){ //coloquei este valor para testar                  

                echo "<tr>";
                echo "<td><input type='text' name='codigo_tipo[]' id='codigo_tipo[]' style='border:none; width:100%; background-color: transparent;'</td>";
                echo "<td><input type='text' name='descricao[]' id='descricao[]' value='' style='border:none; width:100%; background-color: transparent;'</td>";
                echo "</tr>";
            }
        ?>
        </tbody>

    </table><br>

    <div class='form-group col-lg-3'><!-- Inicio Botão para efetuar registro no Banco de Dados -->
        <input type="submit" class="btn btn-success btn-lg btn-block" name="enviar_tipo" value="Salvar Informações">
    </div>

</form>

save php.

<?php
include("conn.php");

if(isset($_POST['enviar_tipo'])){

    $codigo_produto = $_POST['codigo_produto'];
    $codigo_tipo = $_REQUEST['codigo_tipo'];
    $descricao = $_REQUEST['descricao'];

    $sql_tipo = "SELECT * FROM tipoprod WHERE codigo_produto = '$codigo_produto' ";
    $resulta = $conn->query($sql_tipo);
    $row = $resulta->fetch_assoc();

for($i = 0; $i<count($_POST['codigo_tipo'])AND($_POST['descricao']); $i++) {

if ($resulta->num_rows > 0) {
    $result_produto = "UPDATE tipoprod SET codigo_tipo = '$codigo_tipo[$i]', descricao = '$descricao[$i]' WHERE codigo_produto = '$codigo_produto' ";
} else {
    $result_produto = "INSERT INTO tipoprod (codigo_produto, codigo_tipo, descricao) VALUES ('$codigo_produto', '$codigo_tipo[$i]', '$descricao[$i]')";
}

    $resultado_produto = mysqli_query($conn, $result_produto);
    echo "$result_produto <br>";
}
}
?>
  • use array_filter

  • how would I adapt it in this code? has some link for me to have a base, am beginner in php

  • example $arrayLimpo = array_filter($codigo_type);

  • https://ideone.com/sMzJK0

  • declare the filter array inside for or outside, I know it has to be in save.php but I’m a little lost

  • $type code and $description are the ones that can have certain null values?

  • yes, correct thank you for the comment, I will try to implement in my code

  • $type code = array_filter($_REQUEST['type code']);

  • that your include("Conn.php"); on the index is not in the wrong place not?

  • It connects to the database, the file Conn.php

  • yes I know, it should be before the line $sql = "SELECT * FROM tipoprod";

  • If you put Product Code = 3 and fill 2 lines Code and Description and this product code (3) does not exist in the table it inserts 2 lines with same product code. Then next time if you put product code 3 and fill in several lines it will update all rows of the table with code = 3 by the values of the last line of the form

  • But that’s exactly what I want, if you put in five types and descriptions, they have to be linked to the product code, and then if you want to change instead of adding them, they would have that facility. thank you

Show 8 more comments

1 answer

2


To avoid the null is so

 $codigo_tipo = array_filter($_REQUEST['codigo_tipo']); 
 .........
 .........
 for($i = 0; $i<count($codigo_tipo)AND($_POST['descricao']); $i++) {
 .........

array_filter - Filter array elements using a callback function, if no callback is provided, all array entries equal to FALSE will be removed.

Example array_filter() without callback

$entry = array(
         0 => 'foo',
         1 => false,
         2 => -1,
         3 => null,
         4 => ''
      );

print_r(array_filter($entry));

The above example will print:

Array
(
  [0] => foo
  [2] => -1
}
  • Thanks, I did there and it worked out guy really worth. However if I select the value I filled after entering it does not strange update

  • When it is only a type and description it inserts and updates, but when there are 3 types and Description linked to a product it only inserts and then if I want to change only the first line it update in the 3

  • So in case you insert only 1 type and description linked to a product code it inserts and changes, but if I link 3 types and descriptions to a product code it just inserts and when I try to update it changes all types and descriptions, or if I try to insert one more row after just inserting one into the database it understands that the second line updates the first and does not insert

  • @Victort. I paid attention to that detail in a comment there on your question. This is already a case to be solved in the table structure, INSERT and UPDATE. Maybe a WHERE product code = '$product code' AND .....

  • WHERE code_product = '$code_product' AND code_type = '$code_type' ?

  • then, you would have to have something unique for each record and put in the Where clause of the update to not affect them all. The way it is WHERE codigo_produto = '$codigo_produto' update all records where product code_product = '$product code_product'` something like this, where product code_product = '$product code_product' AND that = '$that'

  • thanks I’ll try to fix my update

Show 2 more comments

Browser other questions tagged

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