user799100
user799100

Reputation: 121

delete from database not working

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#load').hide();
});

$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;

$.ajax({
   type: "POST",
   url: "delete.php",
   data: string,
   cache: false,
   success: function(){
    commentContainer.slideUp('slow', function() {$(this).remove();});
    $('#load').fadeOut();
  }

 });

return false;
    });
});


</script>



<?php

include('config.php');
$sql=mysql_query("SELECT * FROM messages ORDER BY mes_id DESC LIMIT 20");
while($row=mysql_fetch_array($sql))
        {
        $msgID= $row['mes_id'];
        $msg= $row['msg'];

?>

<div id="<?php echo $msgID; ?>"  align="left" class="message_box" >
<span class="number"><?php echo $msgID; ?></span><?php echo $msg; ?> 
 <a href="delete.php" class="delete">x</a>
</div>

<?php
}

?>

I have coded this to show entries from database and a delete button to show in every div. delete.php includes code

<?php 
include('config.php');
echo $id=$_REQUEST['msgID'];
$sql="delete from messages where mes_id='$id'";
$res=mysql_query($sql) or die(mysql_error());

?>

but it is not working. I am not able to delete entry from database..

Upvotes: 0

Views: 209

Answers (5)

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91942

Watch out for SQL injections! Use intval on $id before inserting it into your query, to make sure it's an integer.

Upvotes: 0

YonoRan
YonoRan

Reputation: 1728

Your data is wrong: instead of:

data: string,

Where string is:

var string = 'id='+ id ;

Data should be in Key/Value pairs. so:

data: msgID : id

I made it into msgID because your $_REQUEST['msgID'] is calling msgID.

Upvotes: 0

James Allardice
James Allardice

Reputation: 165991

At first glance, I think you want to change this line:

var id = $(this).attr("id");

Into:

var id = $(commentContainer).attr("id");

Because this refers to the clicked link, which does not have an id attribute.

In delete.php you are looking for $_REQUEST['msgID'] but you are using id (not msgID) when you post the request, so you will need to change that to match as well.

Upvotes: 1

Raoul
Raoul

Reputation: 3889

In addition to Subdiggers answer, nice potential for SQL Injection, see: http://php.net/manual/en/security.database.sql-injection.php

Upvotes: 1

Subdigger
Subdigger

Reputation: 2193

check your request var_dump($_REQUEST) you send var string = 'id='+ id ; and trying to receive $_REQUEST['msgID'] just change to $_REQUEST['id']

Upvotes: 2

Related Questions