DELETE FROM users WHERE user_id = $ id

4

I have a script of simple PHP + MySQL query:

<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 script excluir.php

<?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 can not delete records from the database. What am I doing wrong?

    
asked by anonymous 30.01.2015 / 13:02

3 answers

5

In the delete.php in addition to the already been spoken, the call was missing correctly, change:

mysqli_query($strSQL);

for

$mysqli->query($strSQL);

mysqli can be used in object-oriented or procedural mode, avoid mixing the styles, in the procedural model it is mandatory to pass the connection as the first argument in the functions, see the example of query

To avoid sql injection as you mentioned you can change your code to this form:

$id = $_GET['user_id'];

$strSQL = "DELETE FROM users WHERE user_id = ?";
$stmt = $mysqli->prepare($sql); //prepara e transforma a string em uma consulta
$stmt->bind_param('i', $id); //informa que será enviado um integer ao banco
if($stmt->execute() === false){ // efetua a operação
   echo $stmt->error;
}

While doing tests in the code, it comments on the redirection lines so you can see the errors.

bind_param - manual

prepare - manual

    
30.01.2015 / 13:18
9

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

    
30.01.2015 / 13:04
4

The problem is in select, you are not selecting records from the database, you are just returning the values user_id, user_name, user_email, try to take the single quotation marks from Select, leaving:

 // Executa uma consulta
 $sql = "SELECT user_id, user_name , user_email FROM users";
    
30.01.2015 / 13:23