Forum Moderators: coopster

Message Too Old, No Replies

Deleting multiple rows

via checkboxes

         

Tym99

11:47 pm on Mar 7, 2005 (gmt 0)

10+ Year Member



I am wanting to create a page that will list the headings of all the news items in a table, along with a checkbox to mark the row containing the article for deletion upon submission of the form. I have the form working. It's the code to delete the rows on submission that I'm having trouble getting started. If it was only one article at a time I could probably do it, but trying to figure out how to process all the selected checkboxes is kinda throwing me off and I'm not sure how to start. Any ideas?

Thanks!

jatar_k

11:53 pm on Mar 7, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



well if you pass the article_id for each individual article to be deleted then you can put the article_id's into a string seperated by commas then use them in your delete query

$a_ids = '1,3,7,10';
$sql = 'delete from mytable where article_id in (' . $a_ids . ')';

you would have to use a loop through the $POST array to get the checkbox values to construct the $a_ids var, as opposed to the explicit example above. ;)

Tym99

3:28 am on Mar 8, 2005 (gmt 0)

10+ Year Member



Since I'm new to this, I'm trying to think of the best way to acomplish that. In theory if I gave the select boxes a "name" of the article id number and the did a for loop like this:

for (i=1;i<$num_rows;i++){
if ($_POST[i]) {
// and let's say the query to delete the row goes here;
}
}

Something like that SHOULD work, correct?

rlkanter

5:06 am on Mar 8, 2005 (gmt 0)

10+ Year Member



I've done something similar, here is what I did:

Each line on the form has this on it (you can use checkboxes instead of radio if you want obviously)

echo '<input type=radio name="delete'.$myrow['yourid'].'" value="0">';

And then when deleting go cycle through all of them and append it to some string with something like this

if( $_POST['postid'.$i] == 1 ){
if ( $to_delete ) $to_delete .=','.$i;
else $to_delete = $i;
}

And then simply run the query like Jatar suggested

$sql = 'delete from mytable where article_id in (' . $to_delete . ')';

(sorry if this code doesn't work, but it should give yout an idea of where to start)

Tym99

6:18 am on Mar 8, 2005 (gmt 0)

10+ Year Member



Okay.... this is what I came up with. The problem is that it will delete everything except two entries that I have in there. No matter what I cannot get those rows removed.


<?php
include("config.php");

if(isset($_POST['submit']))
{
$username = $_POST["username"];
$password = $_POST["password"];

$result = MYSQL_QUERY("SELECT * from abomination_users WHERE username='$username'and password='$password' LIMIT 1") or die (mysql_error());

if (mysql_num_rows($result)>0)
{

$result = mysql_query("SELECT * FROM abomination_news");
$num_rows = mysql_numrows($result);
for ($i=1;$i<=$num_rows;$i++) {
if ($_POST[$i]) {
$result = mysql_query("DELETE FROM abomination_news WHERE id =".$i) or die('Could not delete.');
}
}
echo "The selected news articles have been deleted";
}
else
{
echo "Name and password not found or not matched";
}
}

else
{
?>
<form method="post" action="<?php echo $PHP_SELF?>">
<table align="center">
<tr>
<td>Name:</td>
<td><input type="text" name="username"></td>
<td>Password:</td>
<td><input type="password" name="password"></td>
</tr>
</table>

<div style="height:225px;width:500px;" class="contentBox">
<table align="center">
<tr><th>Select</th><th>News Subject</th><th>Date Posted</th></tr>
<?php

$result = mysql_query("SELECT * FROM abomination_news ORDER BY date DESC");
while($r=mysql_fetch_array($result))
{
$headline=$r["headline"];
$date=$r["date"];
$body=$r["body"];
$id=$r["id"];
echo "<tr><td><input type='checkbox' name='$id'></td><td>$headline</td><td>$date</td></tr>";

}

mysql_close();
?>

</table>
</div><br>
<input type="submit" name="submit" value="Delete the Selected News Articles">
</FORM>
<?php
}
?>

grandpa

7:53 am on Mar 8, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Are you getting the 'Could not delete' message?

$result = mysql_query("DELETE FROM abomination_news WHERE id =".$i) or die('Could not delete.');

".$i doesn't look right to me. You might try this instead.

$result = mysql_query("DELETE FROM abomination_news WHERE id ='$i') or die('Could not delete.');

rlkanter

8:26 am on Mar 8, 2005 (gmt 0)

10+ Year Member



A good way to test sql queries is to first divide them into two parts, the $sql = string, and then the mysql query itself.

If you run into a problem simply echo out the $sql, and then paste it into the cli mysql prompt and see what it says. This has saved me on numerous locations. It looks what the above poster has said is probably the problem though.

Tym99

5:21 pm on Mar 8, 2005 (gmt 0)

10+ Year Member



That didn't work either. And no, I'm not getting the error message.

I think I may know the problem however I'm not sure what to do about it.

As you can see in my for loop it goes for as long as $1<=$num_rows

Well I only have two rows now, because I was testing the script and deleting stuff before. So I'm assuming $i will only go until it equals 2. However, the id of the two remaining articles are 6 and 8. So in theory they aren't even being reached in the loop. So what I need is to either a) Renumber the id upon deletion or b) find a way to get the highest id number and use that in the for loop instead on $num_rows.

jatar_k

5:32 pm on Mar 8, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



well I looked at your checkbox and there was no value so i wanted to be sure and used this quick test script

<? 
if (isset($_POST['subit'])) {
echo '<pre>';
print_r($_POST);
echo '</pre>';
}
?>
<p><form name="testcheck" method="post" action="<?= $_SERVER['PHP_SELF']?>">
<?
for ($i=1;$i<=4;$i++) {
echo "<br><input type='checkbox' name='$i'> check $i";
}
?>
<p><input type="submit" name="subit" value="sub it">
</form>

when I checked all of the checkboxes and submitted it the result was as I suspected

Array
(
[subit] => sub it
)

so as there is no value attributed to each checkbox there is nothing passed in the $_POST array. So...

so I changed the checkbox output and added, instead of print_r() a little function to construct the delete query. This is obviously an example and won't work as is in your script but will demonstrate the logic. I used shorthand in that first example and hev removed it in this second example so you should be able to upload and run this test script as is.

<?php
if (isset($_POST['subit'])) {
//echo '<pre>';
//print_r($_POST);
//echo '</pre>';
$cnt = 1;
$ids = '';
while(isset($_POST['check' . $cnt])) {
$ids .= $_POST['check' . $cnt] . ',';
$cnt++;
}
$ids = substr($ids,0,strlen($ids)-1);
$sql = 'delete from mytable where id in (' . $ids . ')';
echo '<p>',$sql;
}
?>
<p><form name="testcheck" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<?php
for ($i=1;$i<=4;$i++) {
echo "<br><input type='checkbox' name='check$i' value='$i'> check $i";
}
?>
<p><input type="submit" name="subit" value="sub it">
</form>

you can uncomment the print_r at the top to see the actual contents of the $_POST array. I have no idea what I am really testing so I used a little fancy variable construction to construct my ids. This may not be necessary because you actually know what you are looking for and can construct the vars you are sending in the $_POST in such a way that you know how to measure them.

As I said this is an example to demonstrate how it would be done.

the substr function is used to chop the trailing comma from my string of id's as we always concatenate a comme after an id.

also when you do the mysql_query write it this way to return the error from mysql if there is one.

$result = mysql_query($sql) or die('Could not delete: ' . mysql_error());

does that help clarify the process?

Tym99

9:20 pm on Mar 8, 2005 (gmt 0)

10+ Year Member



It helps me understand a little better and seems a lot more efficient than what I have, thanks.

However, I don't understand what the relevance of having the "value" on the select box is. Neither my code or your code seems to make use of it.

The problem still exists of my ids in the database being 6 and 8. Unless I can figure out some way to have the database renumber the ids after rows are deleted my current problem still seems to exist.

jatar_k

10:31 pm on Mar 8, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



the $_POST array is made up of key value pairs, if it has no value it will not appear in the $_POST array. It won't matter whether it was checked or not.

You can simulate/verify this by running the 2 test scripts I posted individually.

Give me a few minutes to build a more explicit example. ;)

jatar_k

10:38 pm on Mar 8, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



so if you change your output to be this way

$result = mysql_query("SELECT * FROM abomination_news ORDER BY date DESC");
$rowcount = 1;
while($r=mysql_fetch_array($result)) {
$headline=$r["headline"];
$date=$r["date"];
$body=$r["body"];
$id=$r["id"];
echo "<tr><td><input type='checkbox' name='check",$rowcount,"' value='",$id,"'></td><td>",$headline,"</td><td>",$date,"</td></tr>\n";
$rowcount++;
}
echo '<input type="hidden" name="lastcheck" value="',$rowcount-1,'">';

now we have told the script in the form action how many checkboxes there are as well as passing the id in the value portion of the checkbox. So we can now change our processing to reflect this.

<?php 
if (isset($_POST['subit'])) {
$cnt = 1;
$lastcheck = $_POST['lastcheck'];
$ids = '';
while($cnt <= $lastcheck) {
if (isset($_POST['check' . $cnt])) $ids .= $_POST['check' . $cnt] . ',';
$cnt++;
}
$ids = substr($ids,0,strlen($ids)-1);
$sql = 'delete from mytable where id in (' . $ids . ')';
echo '<p>',$sql;
}
?>

see if that works better, I didn't test this I just whipped it together.

Tym99

1:12 am on Mar 9, 2005 (gmt 0)

10+ Year Member



AH HA! I get it now.

I have to make some small modifications but I got it working. Thanks a lot. You're going on my Christmas Card list lol.