Search code examples
phpmysqlsqlformssql-delete

Can't delete record from MySQL database using PHP and HTML Form


I'm trying to create a form on a webpage, which takes an id number entered by the user, and deletes the corresponding record in a database. I'm unable to get it working.

This is the delete code which isn't working:

<?php 

    if (isset($_POST['deleteSubmit'])) { 

        $details = $conn->real_escape_string($_POST['deleteNum']); 
 
        $deleteSQL = "DELETE FROM userName WHERE id = '$details'"; 
 
        $result = $conn->query($deleteSQL); 
     
        if (!$result) { 
            echo 'Error!';
            exit($conn->error); 
        }  else { 
            header('Location: index.php'); 
            exit; 
        }
    }

?>

<h4>DELETE NAME (DELETE)</h4>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  <label for="num">Enter User Reference to be Deleted:</label><br>
  <input num="deleteNum"type="number"><br>
  <input num="deleteSubmit" type="submit" value="Delete">
</form> 

For reference, this is the post code which is working (it's being used to add names to the database):

<?php 

    if (isset($_POST['nameSubmit'])) { 
        $details = $conn->real_escape_string($_POST['newName']); 
 
        $insertSQL = "INSERT INTO userName (name) VALUES ('$details')"; 
 
        $result = $conn->query($insertSQL); 
     
        if (!$result) { 
            echo 'Error!';
            exit($conn->error); 
        }  else { 
            header('Location: index.php'); 
            exit; 
        }
    }

?>


<h4>ENTER NAME (POST)</h4>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  <label for="fname">Enter Name:</label><br>
  <input name="newName"type="text"><br>
  <input name="nameSubmit" type="submit" value="Submit">
</form> 


The database connection file is being called in both programs and is working for the post.php element, which is why I haven't included it or reference to it.

The database has one table called userName which contains two columns id (which is auto incremented) and name.

I've tried changing some of the syntax on the delete.php file with no success. I've ran the $deleteSQL code directly in my database and it works.

I see no error messages when enter an id and click the delete button.


Solution

  • For anyone who reads this in future, the query was solved by @kenlee;

    (1) Change num="deleteSubmit" to name="deleteSubmit"

    (2) change num="deleteNum" type="number" to name="deleteNum" type="number"

    (3) Please use paratemerized prepared statement in your queries