Error returning database records

Asked

Viewed 69 times

0

Good evening everyone, I have the following error when returning the database data: "Warning: mysqli_fetch_assoc() expects Parameter 1 to be mysqli_result, null Given in"

Follows the sources:

php connection.

<?php 
require 'config.php';
//conexão com BD
$conn = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
if ($conn->connect_error) {
    die ('Conexão falhou (' . $conn->connect_errno . ') '
        . $conn->connect_error);
}

if (mysqli_connect_error()) {
    die('Conexão Falhou (' . mysqli_connect_errno() . ') '
                . mysqli_connect_error());
}
?>

Screen source:

<?php
session_start();
require 'database/seguranca.php';
?>

<title>SGTriagH - Especialidades</title>

<?php
  include "include/commom-css.php";
  include "css/padrao.css";

  $existe   = '';

  if(isset($_GET['valor'])) {
    if (!empty($_GET['valor'])) {
      require "database/conexao.php";
      $existe   = true;

      $campo    = $_GET['campo'];
      $condicao = $_GET['condicao'];
      $valor    = $_GET['valor'];

      $where    = '';

      if ($campo == 1) {        // Cod. Usuario
        $where = "descricao LIKE '%".$valor."%'";
      }else if ($campo == 2) {   // Cod. Pessoa
        $where = "tipo ".$condicao." '".$valor."'";
      }

      $query = "SELECT * FROM tb_especialidades WHERE $where";

      if ($valor == '') {
        $query = "SELECT * FROM tb_especialidades";
      }

      $result = mysqli_query($conn, $query);
    }
  }
?>

<script type="text/javascript" language="javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" language="javascript">

  //função para jogar os valores do filtro na url
  $(function($) {
    $('#buscar').click(function(){
      var _campo    = $("#campo").val();
      var _condicao = $("#condicao").val();
      var _valor    = $("#valor").val();

      window.location = "EspecialidadeLST.php?campo=" + _campo + "&condicao=" + _condicao + "&valor=" + _valor;

    })
  });

  //função para desabilitar o campo condição quando a pesquisa utilizar "LIKE"
  function verificaSelect(){
    var campo    = document.getElementById("campo").value;
    var condicao = document.getElementById("condicao");

    condicao.disabled = false;
    $("#condicao").val('=');

    if (campo == 2) {             // Tipo
      condicao.disabled = false;
      $("#condicao").val('=');
    } else if (campo == 1) {      // Descricao
      condicao.disabled = true;
      $("#condicao").val('');
    }
  }

  window.onload = function(){
    condicao.disabled = true;
    $("#condicao").val('');
  }
</script>

<?php
  include "include/Navbar.php";
?>

<div class="container-fluid"><!--Container-->
  <div class="row"><!--Row principal-->

    <?php
      include "include/Sidebar.php";
    ?>
    <div class="alert alert-success flutuar" role="alert" id="mensagemSucesso" style="display: none;">...</div>
    <div class="alert alert-danger flutuar" role="alert" id="mensagemErro" style="display: none;">...</div>
    <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"><!--Main-->
      <div class="row">
        <div class="col-sm-3"><h1 style="margin-top: 0px;">Especialidades</h1></div>
        <div class="pager" style="margin-top: 0px; border-bottom: 1px solid #eee">
          <li class="previous"><a href="EspecialidadeMNT.php"><span class="glyphicon glyphicon-plus-sign voltar"></span> Novo</a></li>
        </div>
      </div>
      <!--Filtros-->
      <div class="row card-filtro">
        <div class="col-sm-3">
          <span>Campo</span></span>
          <select id="campo" name="campo" onchange="verificaSelect();" class="form-control" tabindex="1" title="Selecione o campo para filtrar a consulta" autofocus>
            <option value="1">Descrição</option>
            <option value="2">Tipo</option>
          </select>
        </div>
        <div class="col-sm-3">
          <span>Condição</span></span>
          <select id="condicao" name="condicao" class="form-control" tabindex="2" title="Selecione a condição para filtrar" disabled>
            <option value="=">Igual</option>
            <option value="<>">Diferente</option>
            <option value=">">Maior</option>
            <option value=">=">Maior ou igual</option>
            <option value="<">Menor</option>
            <option value="<=">Menor ou igual</option>
          </select>
        </div>
        <div class="col-sm-3">
          <span>Valor</span>
          <input id="valor" name="valor" type="text" class="form-control text-uppercase" maxlength="60" tabindex="3" title="Informe o valor a ser consultado">
        </div>
        <div class="col-sm-3 alinharBtnFiltro">
          <a href="#" id="buscar" name="buscar" title="Consultar usuário" tabindex="4"><span class="glyphicon glyphicon-search icon-busca"></span></a>
        </div>
      </div>
      <!--/Filtros-->
      <div class="row">
        <table class="table table-striped"><!--Tabela-->
          <thead>
            <tr>
              <th>Ações</th>
              <th>Descrição</th>
              <th>Tipo</th>
            </tr>
          </thead>
          <tbody>
            <!-- PREENCHENDO A TABELA -->
            <?php
              if ($existe == '') {
                require "database/pessoas/popula_especialidade.php";
              }
              while ($popula = mysqli_fetch_assoc($result)) {
                if ($popula['tipo'] == 'M') {
                  $tipoGrid = 'Médico';
                }else{
                  $tipoGrid = 'Enfermeiro';
                }
                echo "<tr><td>".
                     "<a href='EspecialidadeMNT.php?id=".$popula['idEspecialidade']."' id='altera'>"."<span class='glyphicon glyphicon-pencil icon-action-table'>"."</span></a>".
                     "</td><td>"
                     . $popula['descricao']
                     . "</td><td>"
                     . $tipoGrid
                     . "</td></tr>";
              }
            ?>
          </tbody>
        </table><!--/Tabela-->
      </div>
    </div><!--/Main-->
  </div><!--/Row principal-->
</div><!--/Container-->

<?php
    include "include/commom-js.php";
?>

I put some Snippets to "debug" the code and return me the following information:

Query: SELECT * FROM tb_especialidades WHERE tipo = 'M'

$result:

mysqli_result Object
(
   [current_field] => 0
   [field_count] => 3
   [lengths] => 
   [num_rows] => 3
   [type] => 0
)

That is, it is returning the records, but in while, it is not able to read from the array

1 answer

0

The method mysqli_fetch_assoc($result) to fetch the data is related to the Procedure Style of accessing the results, while mysqli($dbhost, $dbuser, $dbpassword, $dbname) to open the connection is related to Object-Oriented Style.
I suggest choosing one of the shapes and using it throughout the process.
As a reference, I give the examples in mysqli-result.fetch-Assoc.php

  • But that doesn’t answer the question.

Browser other questions tagged

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