I am trying to make a PHP script that fetches records from the database, the fetching is working fine but the problem is that when I click DELETE BUTTON, it deletes all the records from the database, what I need to do here is to delete a specific record (the record on the row only), how can I do that?
Here is my code:
<table width="99%" border="0">
<tr>
<td align="center">ID</td>
<td align="center">Username</td>
<td align="center">EDIT</td>
<td align="center">DELETE</td>
</tr>
<?
while ($fetch=mysql_fetch_array($q))
{
?>
<tr>
<td align="center"><? echo $fetch['useId']; ?></td>
<td align="center"><? echo $fetch['userUserName']; ?></td>
<td align="center"><? echo $fetch['useId']; ?></td>
<td align="center"> <input name="delete" type="submit" value="DELETE " onclick="<? mysql_query("DELETE FROM user WHERE useId = ". $fetch['useId'] ."") ?> "/></td>
</tr>
<? } ?>
</table>
As jeroen noted in the comments, you’re mixing up your PHP and JS. You cannot run PHP on a page by invoking a JS function since the PHP is parsed before the page is displayed. What you need to do is use your onClick event to post data back to the page so that it reloads and calls the code to delete the row:
What I’ve done here is modified your code to add a check for the POST variable useId when the page loads. This will exist once the page has been submitted by the form. (I’m assuming you’re using method=”POST” in your form, if you’re using GET then update accordingly). Note that the delete query should really be run before you rurn your $q query so that you don’t see the deleted people in your list after the page refreshes.
I’m also checking that useId is numeric (assuming your user IDs are numeric) as a security check to make sure someone doesn’t send bogus data to your query. Finally I added the hidden field to your form containing the user ID.
EDIT: Forgot to also state that each row in your table needs to be a separate form for this to work properly since you want only the userID for that row to be send as the useID value. Or alternatively you can use JS to determine which row you are deleting and tack on the userID as a GET var.