Show a table header only once

0

I needed help in organizing the table that will be exposed. I wanted it to be a part up identifying the fields (once only). The fields are:

  • ID
  • VAGA
  • WALK
  • APARTMENT
  • NAME
  • MODEL
  • COR

Here's my code:

mysql_connect("localhost","root","");
mysql_select_db("clientes");

$busca = $_GET['busca'];
if($busca != "") {
    $sql = "SELECT * FROM clientes WHERE nVaga LIKE '%$busca%' ORDER BY nVaga ASC ";
    $query = mysql_query($sql) or die( mysql_error() );

        //variavel para zebrar as linhas
        $cont = 0;
        while($row = mysql_fetch_object($query)) {
            //faz a diferenciação das cores para as linhas dos resultados
            if($cont %2 ==0) {
                $cor = "#EDEDED";
            } else {
                $cor = "#FFFFFF";
            }
            echo "<div style='background:$cor'>";

// Atribui o código HTML para montar uma tabela 

        $tabela = "<table border='1'> 
            <thead> 
                <tr> 
                    <th>$row->id</th>
                    <th>$row->ap</th>
                    <th>$row->andar</th>
                    <th>$row->nomeDono</th>
                    <th>$row->modeloCarro</th>
                    <th>$row->cor</th>
                </tr> 
            </thead>
            <tr>";
            echo $tabela; 
            $cont ++;
        }
    }
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>BUSCAR PELA VAGA</title>
<script>

//função para pegar o objeto ajax do navegador
function xmlhttp()
{
    // XMLHttpRequest para firefox e outros navegadores
    if (window.XMLHttpRequest)
    {
        return new XMLHttpRequest();
    }

    // ActiveXObject para navegadores microsoft
    var versao = ['Microsoft.XMLHttp', 'Msxml2.XMLHttp', 'Msxml2.XMLHttp.6.0', 'Msxml2.XMLHttp.5.0', 'Msxml2.XMLHttp.4.0', 'Msxml2.XMLHttp.3.0','Msxml2.DOMDocument.3.0'];
    for (var i = 0; i < versao.length; i++)
    {
        try
        {
            return new ActiveXObject(versao[i]);
        }
        catch(e)
        {
            alert("Seu navegador não possui recursos para o uso do AJAX!");
        }
    } // fecha for
    return null;
} // fecha função xmlhttp

//função para fazer a requisição da página que efetuará a consulta no DB
function carregar(nome)
{
    a = document.getElementById('busca').value;
    var tp = document.forms[0].elements[nome];
    for(i=0; i < tp.length; i++ ) {
        if (tp[i].checked == true) 
           var t = tp[i].value;
    }

    ajax = xmlhttp();
    if (ajax)
    {
        ajax.open('get','busca.php?busca='+a+'&tipo='+t, true);
        ajax.onreadystatechange = trazconteudo; 
        ajax.send(null);
    }
}

//função para incluir o conteúdo na pagina
function trazconteudo()
{
    if (ajax.readyState==4)
    {
        if (ajax.status==200)
        {
            document.getElementById('resultados').innerHTML = ajax.responseText;
        }
    }
}

</script>
</head>

<body>
<form id="form1" action="" method="post">
    Tipo de busca:<br />
    <input type="radio" name="tipo" value="1" id="tipo" checked="checked"/> Inicia com: <br />
    <input type="radio" name="tipo" value="2" id="tipo" /> Contenha: <br />
    <input type="radio" name="tipo" value="3" id="tipo" /> Termine com: <br /><br />
    Buscar carro: <input type="text" name="busca" id="busca" value="" onkeyUp="carregar('tipo')"/>
</form>
<p>&nbsp;</p>
Resultado da busca: <br>
<div id="resultados" style="border:1px solid #CCCCCC; width:300px;">
</div>
</body>
</html>
    
asked by anonymous 03.11.2014 / 15:34

2 answers

2

The problem is that when you use this code, you are mounting multiple tables:

$cont = 0;
while($row = mysql_fetch_object($query)) {
   if($cont %2 ==0) {
      $cor = "#EDEDED";
   } else {
      $cor = "#FFFFFF";
   }
   echo "<div style='background:$cor'>";

   $tabela = "<table border='1'> 
      <thead> 
      <tr> 
      <th>$row->id</th>
      <th>$row->ap</th>
      <th>$row->andar</th>
      <th>$row->nomeDono</th>
      <th>$row->modeloCarro</th>
      <th>$row->cor</th>
      </tr> 
      </thead>
      <tr>";
   echo $tabela; 
   $cont ++;
}

Being that you could just mount the lines within the loop:

echo '<table border="1">';
echo '<tr><th>ID</th><th>AP</th><th>ANDAR</th><th>NOME</th><th>MODELO</th><th>COR</th></tr>';
$cont = 0;
while($row = mysql_fetch_object($query)) {
   if($cont %2 ==0) {
      $cor = "#EDEDED";
   } else {
      $cor = "#FFFFFF";
   }
   // Mantive quase a sintaxe original, mas o certo é fazer isso mais organizado
   // e de preferencia usar classes, em vez da gambiarra de style.
   echo "<tr style='background:$cor'> 
      <td>$row->id</td>
      <td>$row->ap</td>
      <td>$row->andar</td>
      <td>$row->nomeDono</td>
      <td>$row->modeloCarro</td>
      <td>$row->cor</td>
      </tr>";
   // echo $linha; // isso pode simplesmente ir para uma TD igual o resto.
   $cont ++;
}
echo "</table>";
    
03.11.2014 / 15:47
2

You have to get the declaration of table from within while / loop.

First start this piece of HTML:

 $tabela = "<table border='1'> 
    <thead> 
        <tr> 
            <th>ID</th>
            <th>VAGA</th>
            <th>ANDAR</th>
            <th>APARTAMENTO</th>
            <th>NOME</th>
            <th>MODELO</th>
            <th>COR</th>
        </tr> 
    </thead>
    <tbody>";

Then inside your while / loop you can add more HTML to this initial:

// dentro do loop
$tabela.= "<tr style='background: $cor'>
    <td>".$row['ID']."</td>
    <td>".$row['VAGA']."</td>
    <td>".$row['ANDAR']."</td>
    <td>".$row['APARTAMENTO']."</td>
    <td>".$row['NOME']."</td>
    <td>".$row['MODELO']."</td>
    <td>".$row['COR']."</td>
</tr>";

And at the end, outside the loop, close this table and echo:

$tabela.= "</tbody></table>";
echo $tabela;

One suggestion is to use <tr style='background:$cor'> to use CSS classes.

Example:

if($busca != "") {
    $sql = "SELECT * FROM clientes WHERE nVaga LIKE '%$busca%' ORDER BY nVaga ASC ";
    $query = mysql_query($sql) or die( mysql_error() );

 $tabela = "<table border='1'> 
    <thead> 
        <tr> 
            <th>ID</th>
            <th>VAGA</th>
            <th>ANDAR</th>
            <th>APARTAMENTO</th>
            <th>NOME</th>
            <th>MODELO</th>
            <th>COR</th>
        </tr> 
    </thead>
    <tbody>";

    //variavel para zebrar as linhas
    $cont = 0;
    while($row = mysql_fetch_object($query)) {
        //faz a diferenciação das cores para as linhas dos resultados
        $classe = $cont %2 == 0 ? ' class="zebra"' : '';

        $tabela.= "<tr $classe>
            <td>".$row['ID']."</td>
            <td>".$row['VAGA']."</td>
            <td>".$row['ANDAR']."</td>
            <td>".$row['APARTAMENTO']."</td>
            <td>".$row['NOME']."</td>
            <td>".$row['MODELO']."</td>
            <td>".$row['COR']."</td>
        </tr>";
    }
    $tabela.= "</tbody></table>";
    echo $tabela;
}
    
03.11.2014 / 15:51