0

Devo criar um código que o usuário possa digitar o número de linhas e colunas que uma tabela deve ter, e esta tabela deve aparecer para o usuário. Tento este código aqui, mas a tabela não aparece coma as linhas e colunas que eu digitei:

    <?php
echo '<form action="Q.php" method="post">Digite o número de linhas: <input type="text" name="linhas"><br>Digite o número de colunas: <input type="text" name="colunas"><br><input type="submit" value="Construir tabela"></form>';
$linhas = $_POST['linhas'];
$colunas = $_POST['colunas'];
$l = 0;
$c = 0;
echo '<table border="1" width="400px" height="300px">';
while($l <= $linhas){
    $l++;
    echo '<tr>';
    while($c <= $colunas){
        $c++;
        echo '<th></th>';
    }
    echo '</tr>';
}


?>

Desde já, agradeço a resposta

2
  • Seu contador $c não está sendo reiniciado na segunda linha, então ele só cria as colunas da primeira linha... Veja minha resposta abaixo com a correção 3/05/2017 às 22:01
  • Qual é o resultado do seu código? Olhou o código fonte para certificar-se que não foi gerada a tabela? Aliás, para pegar os valores em $_POST você deve certificar-se que foi feita uma requisição POST para o arquivo, além do mais, você precisa reiniciar o contador de colunas a cada linha e encerrar com a tag </table>. O elemento th define o cabeçalho da tabela, então espera-se que só existam apenas na primeira linha. Nas outras, use o elemento td.
    – Woss
    3/05/2017 às 22:02

3 Respostas 3

1

Concentrando-se apenas na parte do PHP, você pode utilizar o laço de repetição for:

function generate_html_table ($rows, $cols)
{
    // Se linha ou coluna for menor ou igual a zero
    // retorna uma string vazia
    if ($rows <= 0 || $cols <= 0)
    {
        return "";
    }

    // Gera a tabela HTML
    $table = "<table>\n";

    // Percorre as linhas
    for($i = 0; $i < $rows; $i++)
    {
        $table .= "\t<tr>\n";

        // Percorre as colunas
        for ($j = 0; $j < $cols; $j++)
        {
            $table .= "\t\t" . sprintf('<%1$s></%1$s>', ($i == 0) ? "th" : "td") . "\n";
        }

        $table .= "\t</tr>\n";
    }

    // Finaliza a tabela
    $table .= "</table>";

    // Retorna o resultado
    return $table;
}

echo generate_html_table(2, 2);

O resultado é:

<table>
    <tr>
        <th></th>
        <th></th>
    </tr>
    <tr>
        <td></td>
        <td></td>
    </tr>
</table>

Agora, juntando com o formulário HTML:

<form method="POST">
    <label>Linhas: <input type="text" name="rows" /></label>
    <label>Colunas: <input type="text" name="cols" /></label>
    <input type="Submit" value="Gerar tabela" />
</form>

<?php

// Verifica se houve uma requisição POST
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
    $rows = 0;
    $cols = 0;

    // Valida o valor informado para linhas
    if (!filter_var($_POST["rows"], FILTER_VALIDATE_INT) === false) {
        $rows = $_POST["rows"];
    }

    // Valida o valor informado para colunas
    if (!filter_var($_POST["cols"], FILTER_VALIDATE_INT) === false) {
        $cols = $_POST["cols"];
    }

    echo generate_html_table($rows, $cols);
}

?>
0

Conforme comentei, você não está reiniciando a variável $c em cada loop das linhas...por isso a tabela só é gerada para a primeira linha! Segue exemplo funcionando:

<form method="POST">
<label>Linhas: <input type="text" name="linhas" /></label>
<br />
<label>Colunas: <input type="text" name="colunas" /></label>
<br />
<input type="Submit" value="Gerar tabela" />
</form>

<?php
$linhas = isset($_POST['linhas']) ? $_POST['linhas'] : -1;
$colunas = isset($_POST['colunas']) ? $_POST['colunas'] : -1;
if($linhas > 0 && $colunas > 0)
    echo "Criando uma tabela de " . $linhas . " linhas por " . $colunas . " colunas";

echo "<table border='1' cellpading='10' cellspacing='10' style='border:1px solid #000; width:" . ($colunas * 100) . "px;height:" . ($linhas * 50). "px;'>";
$l = 0;
while($l < $linhas)
{
    $l++;
    echo "<tr>";
    $c = 0;
    while ($c < $colunas)
    {
        $c++;
        echo "<td style='border:1px dashed #F3F;'>L" . $l . "C" . $c . "</td>";     
    }
    echo "</tr>";   
}
echo "</table>";
?>
0

exemplo - ideone

$numerolinhas = $_POST["linhas"];
$numerocolunas = $_POST["colunas"]; 
$linhas = "";
$linhas = " <tr>\n";
$controws = 0;
$colunas = "";
$colunas = "  <td></td>\n";
$th = "  <th></th>\n";

echo "<table>\n";   
for ($i = 0; $i < $numerolinhas; $i++) {
    echo $linhas;

        if ($i==0){
            for ($k = 0; $k < $numerocolunas; $k++) {
                echo $th;
            }
            echo " </tr>\n<tr>\n";  
        }


        for ($x = 0; $x < $numerocolunas; $x++) {
            echo $colunas;
        }
    echo " </tr>\n";
    $th="";
}   
echo "</table>";
0

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .