Show table header only once

Asked

Viewed 578 times

0

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
  • VACANCY
  • WALK
  • APARTMENT
  • NAME
  • MODEL
  • COLOR

This is 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>

2 answers

2


The problem is that when you use this code, you are mounting several 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 ++;
}

Since I could only assemble her lines inside 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>";
  • that way it was! but I can make the columns to be the same size, aligned?

  • @Angelobotelho first thing, it needs to be the same amount of Ths from the title with the amount of Tds from the loop. If you add a field, you have to put it in both places. Then with CSS and classes you can align as you see fit. I just edited the answer to get it right: echo '<tr><th>ID</th><th>AP</th><th>ANDAR</th><th>NOME</th><th>MODELO</th><th>COR</th></tr>'; in this case there are six Ths, which run the six Tds of the loop. If you move the quantity, move the two places.

  • beauty @Bacco, thank you so much for your attention friend! Bad news is that I don’t understand much of php, or html, let alone css :P I’ll read it here, anything I ask again here! Thanks

2

You have to take the statement from table from within the 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 can add more HTML to that 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, out of the loop, close this table and echo:

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

A suggestion is instead of using <tr style='background:$cor'> 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;
}
  • Here this way didn’t work buddy! But thanks for trying

Browser other questions tagged

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