MYSQL deletes wrong entries.

Post here if you need help with SQL.
Post Reply
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

MYSQL deletes wrong entries.

Post by Temor »

this code right here :
[syntax=php]if(isset($_POST['postid'])){
$deletepost = "DELETE FROM chat WHERE id='".$postid."' ";
mysql_query($deletepost);
}
?>[/syntax]

is supposed to delete the post with the corresponding post id. But instead, it deletes the oldest entry in the database.
Here is the full code for the page if it could help.
[syntax=php]<?php
include('includes/connect.php');




$queryget = mysql_query("SELECT * FROM chat ORDER BY id DESC");



while($row = mysql_fetch_assoc($queryget))
{
$postid = $row['id'];
$name = $row['name'];
$message = $row['message'];
$time = $row['time'];

echo"
<div id='name'>
<b>$name</b> Skrev:</div>
<div id='message'>
".strip_tags($message).$postid." <br /></div>
<div id='time'>
<b> Klockan: $time</b>
";
if (is_admin(mysql_real_escape_string($_SESSION['username'])) == true){
echo "
<form action='index.php?page=chat' method='POST'>
<input type='hidden' value='".$postid."' name='postid' />
<input type='submit' value='delete' />
</form>
"; }
echo"
</div><hr>
";
}

if(isset($_POST['postid'])){
$deletepost = "DELETE FROM chat WHERE id='".$postid."' ";
mysql_query($deletepost);
}
?>[/syntax]

Wasn't too sure if this was a PHP or SQL related question, so Jacek can feel free to move this if needed / wanted :).
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: MYSQL deletes wrong entries.

Post by jacek »

Where do you define $postid ?
Image
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: MYSQL deletes wrong entries.

Post by Temor »

jacek wrote:Where do you define $postid ?

line 13
[syntax=php]while($row = mysql_fetch_assoc($queryget))
{
$postid = $row['id'];[/syntax]
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: MYSQL deletes wrong entries.

Post by jacek »

Well. After the while loop this variable will hav the value of the last row processed. Did you mean to use the value from $_POST ?
Image
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: MYSQL deletes wrong entries.

Post by Temor »

jacek wrote:Well. After the while loop this variable will hav the value of the last row processed. Did you mean to use the value from $_POST ?

Yeah, of course, my bad! :P

Total brainfart!

Edit: It's working like a charm now, thank you :)
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: MYSQL deletes wrong entries.

Post by jacek »

Good good :)
Image
Post Reply