Page 1 of 1

PHP Post Delete

Posted: Thu Nov 25, 2010 11:17 am
by Pazuzu156
In my guestbook, I have it where users can post a comment onto the page. I would like it if there was a button that would delete the post selected. The code i use is:

Code: Select all

if(isset($_POST['del'])) {
$del = mysql_query("DELETE FROM 'guestbook'.'userposts'WHERE'userposts'.'id' = $id LIMIT 1");
}
	echo "
	<table bgcolor='$bgcolor'>
		<tr>
			<td>
				<strong>Posted by: $name ($email) on $date at $time.</strong> <a href='#' name='del'>x</a>
			</td>
		</tr>
		<tr>
			<td>
				".nl2br(strip_tags($message))."
			</td>
		</tr>
	</table>
	";
How do i make this where it will delete just 1 post that the x they click on is in that selected post?

Re: PHP Post Delete

Posted: Thu Nov 25, 2010 1:43 pm
by Celauran
I'd use javascript for something like that, using onclick in each button in the form.

Code: Select all

function deleteEntry(form, id) {
    if (confirm("Are you sure you want to delete this entry?")) {
        var theForm = document.getElementById(form);
        theForm.item_to_delete.value = id;
        theForm.submit();
    }
    else {
        return false;
    }
}

Re: PHP Post Delete

Posted: Thu Nov 25, 2010 2:04 pm
by Pazuzu156
When I make the js, would I post it outside the php?

Re: PHP Post Delete

Posted: Thu Nov 25, 2010 2:09 pm
by Celauran
I typically keep all my js in its own directory and include files as needed, but that's more to keep my file structure somewhat sane. If you'll only be using that function in this one page and would rather have it directly in the page, that will work too.

Re: PHP Post Delete

Posted: Thu Nov 25, 2010 2:13 pm
by Pazuzu156
When I do this, it does the pop up asking if I'm sure, but then nothing happens. When it is suppose to delete, i want each button to delete that one post that the button is associated with. How would I do this without defining an id number and how would i do it without erasing the entire database?

Re: PHP Post Delete

Posted: Thu Nov 25, 2010 2:26 pm
by Celauran
It won't work without defining an ID; that's what tells it which post to delete. Since I assume you're populating your form with information from the database to begin with, you should already have each item's ID.

Code: Select all

<?php while ($row = mysql_fetch_array($res)) { ?>
... 
... 
<input type="button" name="id" onclick="deleteEntry('form_name', <?php echo $row['id']; ?>)" />
<?php } ?>
Once the form has been submitted, you pass the value of $_POST['item_to_delete'] to your DELETE query.

Re: PHP Post Delete

Posted: Thu Nov 25, 2010 2:31 pm
by Pazuzu156
I have my id auto increment each time a post is made. When I have it made, I want the button to be assigned to this value as well. How would I do this, and would it help if I posted my codes into here?

Re: PHP Post Delete

Posted: Thu Nov 25, 2010 2:34 pm
by Celauran
Even if the ID field is auto incremented rather than specified, each post is going to have its own ID. When you're fetching the info to populate your form, make sure the ID is included in your query.

Posting relevant code here might help.

Re: PHP Post Delete

Posted: Thu Nov 25, 2010 2:44 pm
by Pazuzu156
Ok, here goes.

Connect:

Code: Select all

<?php

$guestbook = array(
    "mysqlconnector" => array(
        "host" => "localhost",
        "username" => "root",
        "password" => "",
        "database" => "guestbook",
		"values" => "SELECT * FROM userposts ORDER BY id ASC",
    ),
);

?>
Posts:

Code: Select all

<?php

function connect($to) {
    include("cred.php");
	include("delete.js");
    $connection = mysql_connect($guestbook[$to]["host"], $guestbook[$to]["username"], $guestbook[$to]["password"]) or die ("Connot connect");
    mysql_select_db($guestbook[$to]["database"], $connection) or die ("Connot connect to db");
	$getstuff = mysql_query($guestbook[$to]["values"]) or die ("Invalid Query");
	$rownum = mysql_num_rows($getstuff);
	if($rownum==0) {
	echo "<p>No posts have been made yet. Be the first to make one.</p>";
}
	while($row = mysql_fetch_assoc($getstuff)) {
	//set variables to show in the posts
	$id = $row['id'];
	$name = $row['name'];
	$email = $row['email'];
	$message = $row['message'];
	$date = $row['date'];
	$time = $row['time'];
	
	//set background color variables to set backgrounds to every other table based on id number
	if($id%2) {
		$bgcolor = '#FFFFFF';
	}
	else {
		$bgcolor = '#E1E1E1';
	}
	echo "
	<table bgcolor='$bgcolor'>
		<tr>
			<td>
				<strong>Posted by: $name ($email) on $date at $time.</strong> <input type='submit' name='submit' value='Delete Post' onclick='deleteEntry(form,id);'>
			</td>
		</tr>
		<tr>
			<td>
				".nl2br(strip_tags($message))."
			</td>
		</tr>
	</table>
	";
}


	
    return $connection;
}

connect("mysqlconnector");

?>
Guestbook signing:

Code: Select all

<?php

echo "\n<h1>PHP/MySQL Guestbook</h1>\n<hr />\n";
include("connect.php");
echo "<hr />";

if(isset($_POST['submit'])) {
	$name = $_POST['name'];
	$email = $_POST['email'];
	$message = $_POST['message'];
	$date = date("Y-m-d");
	$time = date("H:i:s");
	
	if($name&&$email&&$message) {
		$postbook = mysql_query("INSERT INTO userposts VALUES('','$name','$email','$message','$date','$time')");
		echo "Please wait...<meta http-equiv='refresh' content='2;guestbook.php'>";
	} else {
		echo "Please fill out the enitre form. Thanks.";
	}
}

echo "
<form action='sign.php' method='post'>
	<table>
		<tr>
			<td valign='top' width='20%'>
				Name:
			</td>
			<td>
				<input type='text' name='name' size='51' maxlength='64'>
			</td>
		</tr>
		<tr>
			<td valign='top'>
				E-Mail:
			</td>
			<td>
				<input type='text' name='email' size='51' maxlength='64'>
			</td>
		</tr>
		<tr>
			<td valign='top'>
				Message:
			</td>
			<td>
				<textarea cols='40' rows='5' name='message' maxlength='600'></textarea><br />
				<input type='submit' value='Post' name='submit'> <input type='reset' name='reset' value='Reset'>
			</td>
		</tr>
		
	</table>
</form>
<form action='guestbook.php' method='POST'>
<input type='submit' value='Cancel'>
</form>
";

?>
I may just be making this out to be harder than it really is. :lol:

Re: PHP Post Delete

Posted: Thu Nov 25, 2010 2:56 pm
by Celauran
A couple of changes:

Code: Select all

<?php

function connect($to) {
    include("cred.php");
        include("delete.js");
    $connection = mysql_connect($guestbook[$to]["host"], $guestbook[$to]["username"], $guestbook[$to]["password"]) or die ("Connot connect");
    mysql_select_db($guestbook[$to]["database"], $connection) or die ("Connot connect to db");
        $getstuff = mysql_query($guestbook[$to]["values"]) or die ("Invalid Query");
        $rownum = mysql_num_rows($getstuff);
        if($rownum==0) {
        echo "<p>No posts have been made yet. Be the first to make one.</p>";
}
        echo "<form id=\"frmPosts\" action=\"\" method=\"post\">
              <input type=\"hidden\" name=\"item_to_delete\" value=\"\" />";
        while($row = mysql_fetch_assoc($getstuff)) {
        //set variables to show in the posts
        $id = $row['id'];
        $name = $row['name'];
        $email = $row['email'];
        $message = $row['message'];
        $date = $row['date'];
        $time = $row['time'];
       
        //set background color variables to set backgrounds to every other table based on id number
        if($id%2) {
                $bgcolor = '#FFFFFF';
        }
        else {
                $bgcolor = '#E1E1E1';
        }
        echo "
        <table bgcolor='$bgcolor'>
                <tr>
                        <td>
                                <strong>Posted by: $name ($email) on $date at $time.</strong> <input type='button' name='submit' value='Delete Post' onclick='deleteEntry(frmPosts, $id);'>
                        </td>
                </tr>
                <tr>
                        <td>
                                ".nl2br(strip_tags($message))."
                        </td>
                </tr>
        </table>
        ";
}
echo "</form>";


       
    return $connection;
}

if ($_POST['item_to_delete'] != '')
{
    $sql = "DELETE FROM guestbook WHERE id = {$_POST['item_to_delete']}";
    mysql_query($sql);
}

connect("mysqlconnector");

?>

Re: PHP Post Delete

Posted: Thu Nov 25, 2010 3:07 pm
by Pazuzu156
Done, but I get this error: Notice: Undefined index: item_to_delete in C:\wamp\www\phphelp\connect.php on line 53

And the js does nothing. Sorry, I'm quick with grasping things, but this is just blowing my mind up. Haha.

Re: PHP Post Delete

Posted: Thu Nov 25, 2010 3:31 pm
by Celauran
I just made a mock database, tested everything, and it's working fine for me. Are you getting any javascript errors? What are they?

Here's the code I used that is working fine:

Code: Select all

<?php

include('include/db.php');  // This is where I establish database connection.

if ($_POST['item_to_delete'])
{
    $sql_del = "DELETE FROM posts WHERE id = {$_POST['item_to_delete']}";
    mysql_query($sql_del);
}

$sql = "SELECT * FROM posts ORDER BY id ASC";
$res = mysql_query($sql);

?>
<html>
    <head>
        <title>Test Page</title>
        <script type="text/javascript" src="include/delete.js"></script>
    </head>
    <body>

        <form id="frmPosts" action="" method="post">
            <input type="hidden" name="item_to_delete" value="" />
            <table>
                <?php while ($row = mysql_fetch_assoc($res)) { ?>
                <tr>
                    <td><?php echo $row['message']; ?></td>
                    <td>
                        <input type="button" name="delete" value="Delete" onclick="deleteEntry('frmPosts', <?php echo $row['id']; ?>);" />
                    </td>
                </tr>
                <?php } ?>
            </table>
        </form>
    </body>
</html>

Re: PHP Post Delete

Posted: Thu Nov 25, 2010 3:45 pm
by Pazuzu156
I just copied your code, got this:
Notice: Undefined index: item_to_delete in C:\wamp\www\phphelp\connect.php on line 5

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\wamp\www\phphelp\connect.php on line 25

Then went back to mine. I'll just work the two together see what I come up with.