Why is the second WHILE not working?

2
$consulta = "SELECT * FROM 'teste' WHERE id='1' ";
<div class="box-header">
          <h2><?php while($d = $con->fetch_array()){ ?>
                <?php echo $d["cnpj_cpf_tab_clientes"];?>
                <?php echo $d["telefone_tab_clientes"];?>                               
                <?php } ?></h2>
        </div>
        <!-- /.box-header -->
        <div class="box-body">
            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                <thead><tr>
                  <th>CNPJ</th>
                  <th>Telefone</th>                   
                  </tr>
                </thead>
                <tbody>
                <?php while($dado = $con->fetch_array()){ ?>
                            <tr>
                            <td><?php echo $dado["cnpj_cpf_tab_clientes"];?></td>
                            <td><?php echo $dado["telefone_tab_clientes"];?></td>
                            </tr>
                <?php } ?>
                </tbody>
                </table>
                <h2>Endereço</h2>
            </div>

Why does the second while($dado..) return no results?

    
asked by anonymous 29.03.2017 / 17:41

1 answer

5

It turns out that fetch_array "consumes" all rows in the first while, ie it changes the internal pointer to the end of the data during the while. That way you need to return the pointer to the first line by putting:

mysqli_data_seek($result, 0);

before the second while

   <div class="box-header">
      <h2>
      <?php 
      $result = $con->query($consulta);
      while($d = $result->fetch_array()){ ?>
            <?php echo $d["cnpj_cpf_tab_clientes"];?>
            <?php echo $d["telefone_tab_clientes"];?>                               
            <?php } ?></h2>
    </div>
    <!-- /.box-header -->
    <div class="box-body">
        <div class="table-responsive">
            <table class="table table-bordered table-striped">
            <thead><tr>
              <th>CNPJ</th>
              <th>Telefone</th>                   
              </tr>
            </thead>
            <tbody>
            <?php 
            mysqli_data_seek($result, 0);
            while($dado = $result->fetch_array()){ ?>
                        <tr>
                        <td><?php echo $dado["cnpj_cpf_tab_clientes"];?></td>
                        <td><?php echo $dado["telefone_tab_clientes"];?></td>
                        </tr>
            <?php } ?>
            </tbody>
            </table>
            <h2>Endereço</h2>
        </div>
    
29.03.2017 / 19:05