php – DELETE FROM users WHERE user_id = $id

Question:

I have a simple PHP+MySQL query script :

<table >
  <tr>
    <td ><h2>GERENCIAR  ANUNCIOS </h2></td>
  </tr>
  <tr>
    <td >

<table >
  <tr>
    <th >ID</th>
    <th >Nome</th>
    <th >Email</th>
    <th >Ação</th>

</tr>
<?php

// Aqui você se conecta ao banco
$mysqli = new mysqli('127.0.0.1', 'root', '', 'login');

// Executa uma consulta
$sql = "SELECT `user_id`, `user_name` , `user_email` FROM `users`";
$query = $mysqli->query($sql);
while ($dados = $query->fetch_assoc()) {
    $id        = $dados["user_id"];
    $nome      = $dados["user_name"];
    $email = $dados["user_email"];

    echo "<tr>
    <td > $id </td>
    <td > $nome </td>
    <td > $email </td>
    <td > <a href='excluir.php?user_id=$id'>excluir </a></td>
    </tr>\n";
    }

echo 'Registros encontrados: ' . $query->num_rows . '<br><br>';

?>
</table>
</td>
</tr>
</table>

And a excluir.php script

<?php
    $mysqli = new mysqli('127.0.0.1', 'root', '', 'login'); 
    $id = 'user_id';

    $strSQL = "DELETE FROM users WHERE user_id = $id";
    mysqli_query($strSQL);

    // Fechar conexão com Banco de Dados
    mysql_close();
    header("Location: index.php");
    ?>

I cannot delete records from the database. what am I doing wrong?

Answer:

You are trying to delete a record that contains the value 'user_id'. Change your excluir.php line 2 to: $id = $_GET['user_id'];

Scroll to Top