WJB
WJB

Reputation: 9

Use a simple form and PHP to delete a mySQL record

I am trying to build a page that will allow the user to enter an employee number via a form and when they hit the "delete" button it will remove the corresponding record. The database is named "Crosshill", the Table is called "Employees" and the field I want to use is "employeeid".

It seems to connect fine to the DB, but the code below doesn't work. When you hit the "Delete" button it returns an error of:

Could not delete data: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE employeeid =' at line 1 Blockquote


<html>
<head>
<title>Delete an Employee</title>
</head>
<body>

<h3>Enter the Employee Number below to delete a record</h3>

<?php
if(isset($_POST['delete']))
{
$dbhost = '####';
$dbuser = '####';
$dbpass = '####';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}

$employeeid = $_POST['employeeid'];

$sql = "DELETE Employees ".
       "WHERE employeeid = $employeeid" ;

mysql_select_db('Crosshill');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not delete data: ' . mysql_error());
}
echo "Deleted data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Employee ID</td>
<td><input name="employeeid" type="number" id="employeeid"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="delete" type="submit" id="delete" value="Delete">
</td>
</tr>
</table>
</form>
<?php
}
?>
</html>

Upvotes: 0

Views: 10872

Answers (2)

sandeep Kumar
sandeep Kumar

Reputation: 121

You are missing "from" after delete.. It should be as DELETE from Employees WHERE condition.

To avoid such situations always do one thing, just echo the sql query and using "exit" after the same to terminate the further execution of the program.

Copy the query from browser and run the same in phpmyadmin or whatever other tool you use..

That practice will help you to find out the root cause of the problem..

Upvotes: 0

BluePsyduck
BluePsyduck

Reputation: 1141

It's DELETE FROM <table> WHERE <condition>, the FROM is missing in your query.

Upvotes: 6

Related Questions