-1

I have a PHP that I am unable to get it to work. Its function is to connect to my db and delete the input email address from the database. But for some reason, the result is always "Data Not Deleted". I am sure of all the details like db connect details and columns names etc. still the code doesn't work.

Code:

<?php

// php code to Delete data from mysql database 

if(isset($_POST['delete']))
{
    $hostname = "localhost";
    $username = "root";
    $password = "";
    $databaseName = "newsletter";

    // get id to delete
    $email = $_POST['email'];

    // connect to mysql
    $connect = mysqli_connect($hostname, $username, $password, $databaseName);

    // mysql delete query 
    $query = "DELETE FROM `email_user` WHERE `email` = $email";

    $result = mysqli_query($connect, $query);

    if($result)
    {
        echo 'Data Deleted';
    }else{
        echo 'Data Not Deleted';
    }
    mysqli_close($connect);
}

?>

<!DOCTYPE html>

<html>

    <head>

        <title> PHP DELETE DATA </title>

        <meta charset="UTF-8">

        <meta name="viewport" content="width=device-width, initial-scale=1.0">

    </head>

    <body>

        <form action="unsub.php" method="post">

            ID TO DELETE:&nbsp;<input type="text" name="email" required><br><br>

            <input type="submit" name="delete" value="Clear Data">

        </form>

    </body>

</html>

Please point out what I am doing wrong in here?

Thanks

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Cody Coderson
  • 411
  • 1
  • 9
  • 21
  • 1
    https://www.w3schools.com/php/php_mysql_delete.asp – TarangP Feb 12 '18 at 07:51
  • 2
    `$email` contains a string, it needs to be in quotes: `'$email'`, in your query. But there are more urgent problems. Do not put this code online! Read up about 'SQL-injection'. – KIKO Software Feb 12 '18 at 07:52

2 Answers2

2

You need to add quotes around $email in your query as it is a string.

$query = "DELETE FROM `email_user` WHERE `email` = '$email'";

Note:- Your code is wide-open for SQL INJECTION.You have to use prepared statements

Help reference:-

mysqli::prepare

PDO::prepare

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
0

Try modifying the query to following:

"DELETE FROM `email_user` WHERE `email` = '$email'"
Amit Merchant
  • 1,045
  • 6
  • 21