Popular table with HTML table data

Asked

Viewed 3,146 times

1

I have a table with 4 columns (name, prova1, prova2, simulated). Suppose you are a teacher, and you wish to post student grades. I return to you the following:

// $l representará o número de linhas que existem
$l = -1;

// $inst2 carrega: SELECT nome, prova1, prova2, simulado FROM alunos

while($dado = mysqli_fetch_row($inst2)) {

      $l+=1;
      $dados[] = $dado;

}
for ($x=0; $x<=$l; $x++) {
 echo "<tr>";
 for ($y=0; $y<=3; $y++) { 
       if ($y==0) {
       echo "<td>".$dados[$x][$y]."</td>";
       } else {       
       echo "<td><input type=\"text\" value=\"".$dados[$x][$y]."\" size=\"6\"></td>";
       }
 }
}
echo "</tr>";
echo "</table>

That is, the ballots of the table in which there are no values registered yet (are null), will have in its content a input for the teacher to insert the student’s note.

My problem is: I want you to have a button so that after the teacher inserts the notes he will click on it and they will be saved in the database.

I even thought of doing so: put the table that appears on the screen inside a form, and put us inputs text a name using the variables $x and $y. And add a column with an id for each row (auto_increment). However, I couldn’t move on. Even though I believe there’s a better way to do it.

PS: I I prefer your help using procedural. Thank you!

  • Want to do this with ajax or load the page again?

  • I want when the teacher submits the data to show him the new table. That is, with the new values inserted by him.

  • Ok, and want to do this with ajax or load the page again?

  • Reload.

1 answer

-1

<!DOCTYPE html>

<html>
    <?php
    require("header.php");

    //iniciar a pesquisa no banco de Dados para povoar a tabela
    //criar a conexão com o banco de dados
    $link = new mysqli('localhost', 'root', '', 'escola');

    if (!$link) {
        die('Connect Error (' . mysqli_connect_errno() . ') '
                . mysqli_connect_error());
    }
    //Selecionar todos os registros da tabela
    $query = "SELECT * FROM alunos" or die("Error in the consult.." . mysqli_error($link));
    $result = $link->query($query);
    $cont=0;
    ?>
    <body>

        <form method="POST" action="gravarNotas.php">
            <table>
                <thead>
                    <tr>
                        <th>Nome</th>
                        <th>prova1</th>
                        <th>prova2</th>
                        <th>simulado</th>
                    </tr>
                </thead>
                <tbody>

                    <!-- iniciando loop para povoar a tabela --> 
<?php
//Criando variável para armazenar os dados
//Adiciona o ID para poder fazer a gravação no banco posteriormente
$tabela = "Notas";
if ($result) {
    while ($row = mysqli_fetch_array($result)) {
        $id = $row['idalunos'];
        //Saber quantos resgistros existem na tabela
        $cont++;
        
        $tabela .= " <tr>"
                . "<td><input type='text' name='nome_$id' id= '{nome_$id}' value='{$row['nome']}' ></td>
                   <td><input type='text' name='nota1_$id' value='{$row['nota1']}' id= '{nota1_$id}'></td>
                   <td><input type='text' name='nota2_$id' value='{$row['nota2']}' id= '{nota2_$id}'></td>
                   <td><input type='text' name='simulado_$id' value='{$row['simulado']}' id= '{simulado_$id}' ></td> "
                . "</tr>";
    }
    
}

echo $tabela;
?>




                </tbody>
            </table>
            <!-- passando para o post a qtd de registros -->
            <input type="hidden" name="totalRegistros" value="<?=$cont;?>">
            <button type="submit">Enviar notas</button>
        </form>
    </body>

</html>

Here you generated the html and inserted the records in the table. When you click "Send notes", the "action" will be executed. So the page to be loaded will be writing Notes.php. This page will write to the database.

<?php
  $link = new mysqli('localhost', 'root', '', 'escola');

    if (!$link) {
        die('Connect Error (' . mysqli_connect_errno() . ') '
                . mysqli_connect_error());
    }
     
    if($_POST && $_POST['totalRegistros'] > 0){
         for($i=1; $i<=$_POST['totalRegistros']; $i++ ){
             
             #apenas para ficar mais compreensível
             $nome = $_POST['nome_'.$i];
             $nota1 = $_POST['nota1_'.$i];
             $nota2 = $_POST['nota2_'.$i];
             $simulado = $_POST['simulado_'.$i];
             
             #executa a gravação no bando de dados
              $query = "UPDATE `escola`.`alunos` SET `nome`=' {$nome}', `nota1`= '{$nota1}', 
                  `nota2`= '{$nota2}', `simulado`= '{$simulado}' WHERE `idalunos`='{$i}'";
;             $result = $link->query($query);
         }
    }
    header('Location: index.php');

  • Can you explain to me what that value is?

  • let’s go: <?=@$name;? > here I state that this part of the code is php, because the rest is html. @ is to prevent php from making an exception if the variable is empty. and the rest is pàopria variable. If you want, you can insert all the logic of searching in the database and feed the variable, before html.

  • A tip, Israel, is nice -even if briefly- to explain why your code solves the problem presented. This helps the current and future reader to read/understand the code/solution. . . . Or more directly, the explanation in your comment should be an edition in the reply.

  • This code of yours is just taking the data from the database and putting it in the table. That’s what I did. There’s the code. What I want is exactly the part you didn’t do. Save what the user insert into the inputs in a database... And another table will have numerous lines, requiring the use of loops.

  • I refactored the code and posted the comments.

Browser other questions tagged

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