Array result returns null

Asked

Viewed 141 times

0

  • I need it from the option selected on <select>, me check in the bank what is related to this option. I did this from way that follows below, but in part $p_id = $result['p_id'];, no return, I have already used this array association code other times and it worked.

  • I also need that all remain hidden until the moment of choice of <option>, after display what I did, with the records. I do not know the that is wrong, but I accept suggestions for solution and thank you from now on.

                      <div class="form-group">
                        <div class="col-sm-3">
                          <label for="exampleInputEmail1">Cliente</label>
                          <select class="form-control m-b-10" required="required" name="e_id" charset="utf-8">
                            <option>Selecione o cliente</option>
                              <?php
                                $select  = "SELECT e_id, nome FROM pessoas"; 
                                $result  = mysqli_query($conexao, $select);
                                while($exibe = mysqli_fetch_assoc($result)){
                                  $e_id = $exibe['e_id'];
                                  echo '<option  charset="utf-8" value = '. $e_id . '>' . $exibe['nome'] . '</option>';
                                }                                    
                                mysqli_free_result($result); 
                              ?>                     
                          </select> 
    
                        </div>                                  
                      </div>
                      </form>
                      <!--<button name="salvar" class="btn btn-success" onclick="showElement();">Pesquisar</button>-->
                      <div id="dados" class="form-group" onload="hideElement();">                                                       
                            <?php
                            if ($e_id <> '') {
                              $select  = "SELECT p_id FROM itens WHERE e_id = '$e_id'";  
                              $result  = mysqli_fetch_assoc(mysqli_query($conexao, $select));
                              $p_id  = $result['p_id'];
                              $select2 = "SELECT descricao where p_id = '$p_id'";
                              $resulta = mysqli_query($conexao, $select2);          
                              if (mysqli_num_rows($resulta) > 0){                            
                              echo '<table class="table table-hover" >
                                  <thead>
                                    <tr>
                                      <th>Descrição</th>
                                  </tr>
                              </thead>
                              <tbody>
                                <tr>';
                                while($exibe = mysqli_fetch_assoc($resulta)){ 
                                    $p_id  = $exibe['p_id'];
                                    echo '<tr>';  
                                      echo '<td value = "">' . $exibe['descricao']      . '</td>';                   
                              }
                            }else{
                              echo '<label for="exampleInputPassword1">Não há registros</label>'; 
                            } 
                          }else{
                            echo '<label for="exampleInputPassword1">Não há registros</label>';
                          }             
                          mysqli_free_result($result);  
                          mysqli_free_result($resulta);                                                                              
                            ?>                                     
                      </tr>
                  </tbody>
              </table>
    
  • Your code doesn’t seem to make much sense (sorry if I didn’t understand it correctly), but you know how to differentiate language client-side of language server-side? PHP is server-side, but it seems that you tried to use it as if it were client-side, such as Javascript.

  • You tried with: do{ //code.... } while($displays = mysqli_fetch_assoc($results));

  • explains your code from above. It’s all on one page only?

  • I agree with @Andersoncarloswoss. I would even do it another way: Put a form with action for the same page and a trigger with jQuery or Javascript to give a submit at the event change of select. If you cannot have a "refresh" in your application, you can do (also) with ajax.

1 answer

0

I need from the option selected in select, I see in the bank what is related to this option.

No way to use the PHP in the client-side (@Andersoncarloswoss).

For that reason, one can:

  • Make a second page that showcase the description according to the id method-tested get form;
  • Submit the form at the event change of <select> with a request AJAX;
  • Show request data (contents of second tab) on a div;

Understanding this, let’s go to the code:

index php.

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>

        <script type="text/javascript">

            $(document).ready(function(){
                $('#slcClientes').on('change', function() {
                    var dados = jQuery( '#fmrClientes' ).serialize();
                    $.ajax({
                        type: "POST",
                        url: $('#fmrClientes').attr('action'),
                        data: dados,
                        success: function(data) {
                            $('#dvAlvo').html(data);
                        }
                    });
                });
            });

        </script>

    </head>
    <body>

        <form id="fmrClientes" action="get_obs.php" method="post">
            <select id="slcClientes" name="cl_id">
                <option selected="selected" disabled="disabled">Selecione:</option>
            <?php

                $conexao = mysqli_connect("host", "usuário", "senha", "banco de dados"); // CONFIGURE!!!
                $res = mysqli_query( $conexao, "SELECT `ClID`, `ClNome` FROM `clientes` LIMIT 0,10;"); // LIMITEI PARA 10 REGISTROS - SOMENTE PARA FINS DE TESTE
                if(mysqli_num_rows($res) > 0)
                {
                    while( $cl = mysqli_fetch_assoc($res) )
                    {
                        echo "<option value=" . $cl['ClID'] . ">" . $cl['ClNome'] . "</option>";
                    }
                }

            ?>
            </select>
        </form>

        <div id="dvAlvo">
            <!-- ALVO DA REQUISIÇÃO AJAX -->
        </div>

    </body>
</html>

get_obs.php

<?php

    $conexao = mysqli_connect("host", "usuário", "senha", "banco de dados"); // CONFIGURE!!!
    $id = $_POST['cl_id'];
    $res = mysqli_query( $conexao, "SELECT `ClOBS` FROM `clientes` WHERE `ClID` = '" . $id . "';");
    $desc = mysqli_fetch_assoc($res);
    echo nl2br( htmlspecialchars( $desc['ClOBS'] ) );

?>

Table structure customers:

+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| ClID    | int(5)       | NO   | PRI | NULL    | auto_increment |
| ClNome  | varchar(150) | YES  |     | NULL    |                |
| ClObs   | text         | YES  |     | NULL    |                |
+---------+--------------+------+-----+---------+----------------+

Remember to set the variable $conexao in both archives!

I also need that all remain hidden until the moment of the choice of option, after displaying what I did, with the records.

As the div target is empty, the content will only be shown on it when selecting some option from select. The trigger is on line 7 of index.php.

The code I developed is 100% functional. Tested with PHP 7. However, I treat the description as observing in my code.

I didn’t care about form validation. Do it yourself. This code is for guidance purposes.

Tip if there are many customers: Instead of making one select showing all registered customers, recommend you create a input[type=text] with autocomplete of jQuery.

  • Thank you, I’ll test!

  • Test there and give a feedback! I’m waiting! If necessary, suggest something to improve the code.

  • It didn’t work, nothing happens!

  • As nothing happens?! Post the error. Even if it is on the console, it should generate some error! This code was tested and worked 100% with me. Maybe it is the name of the tables that is different. You should change there.

  • The value with id of this excerpt: echo "<option value=" . $cl['ClID'] . ">" . $cl['ClNome'] . "</option>"; is ok in html, is filling correct, but in php the following error occurs: Undefined index: $id, because of this when I check with var_dump the result returns null. I don’t understand why php does not receive the id.

  • @R.Gasparin : But vc must be using the variable $id as an index of some vector (array). The correct is the $id receive the value of $_POST['cl_id'], where cl_id is the name of input in your form. If you just copy and paste the code I made, it will work 100%. I tested it here and it’s all ok.

  • In my code I need to capture the id of the first option and use it in the next select to get another id from another table, because what I need to display comes from that second select. In my code, I did it in a way that I can usually capture an id from another table, but not yours for what reason this id is not captured. All that I said is in the code placed in the question.

Show 2 more comments

Browser other questions tagged

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