I can’t delete with PHP, Mysql

Asked

Viewed 75 times

-1

So, I’m a beginner in PHP and I have a question in the following code... when I click the remove button it doesn’t just remove the id from the back of the while, it removes all, anyone could help me?

<?php
    include 'conexao.php';
    session_start();
?>
<html>
    <head>
    </head>
    <body>
        <h1>CRUD - ALUNOS</h1>
        <form action="FrmCadastro.php" method="POST">
            <input type="submit" value="+"/>
        </form>
        <table border="2px">
        <th>Aluno</th>
        <th>Nota</th>
        <th>Turma</th>
        <tr></tr>
        <?php
            $sql = "SELECT * from tbAluno";
            $listarAlunos = mysqli_query($conexao, $sql);

            while($row = mysqli_fetch_assoc($listarAlunos)){
                $id = $row['id'];
                $nome = $row['aluno'];
                $nota = $row['nota'];
                $turma = $row['turma'];
        ?>
            <td>
                <?php echo"$nome"?>
            </td>
            <td>
                <?php echo"$nota"?>
            </td>
            <td>
                <?php echo"$turma"?>
            </td>
            <td>
                <form>
                <input type="submit" value="remover"/>
                    <?php
                        $sql = "DELETE from tbAluno WHERE id = $id";
                        $removerAluno = mysqli_query($conexao, $sql);
                        echo $id;
                    ?>
                </form>
            </td>
            <tr></tr>
        <?php 
            }
        ?>
        </table>
    </body>
</html>
  • The DELETE code is running for each user you selected in the query. To make the code run only when you click the button, you would need to make a form Handling

1 answer

0


Manage.php

  $result = mysqli_query($conn, "SELECT * FROM table ORDER BY id DESC");
            while($row = mysqli_fetch_assoc($result)){ ?>
            <tr>
              <td><?php echo $row['id']; ?></td>
              <td><?php echo $row['title']; ?></td>
              <td><?php echo $row['date']; ?></td>
              <td>
                <a href="delet.php?id=<?php echo $row['id']; ?>" class="btn btn-info btn-xs">
                <i class="fa fa-pencil"></i> Edit
                </a>
              </td>
            </tr>
          <?php } ?>

Delet.php

$id = $_GET['id'];

$sql = mysqli_query($conn, "DELETE FROM table WHERE id='$id'");
$result  = mysqli_fetch_assoc($sql);

header("Location: manage.php");
exit();

Just replicate the code according to your information and purpose, I just did a demonstration.

  • Thank you very much, it worked perfectly and I managed to understand the code. Thank you again!

Browser other questions tagged

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