• 0

PHP Check Box delete Script


Question

I am trying to delete my articles with selected checkboxes but I am having a little issue. When I click the delete button nothing happens, I am not sure where to append the variable, can someone help?

<?php

//include database

require_once('db_config.php');

$tbl_name="articles"; // Table name

$sql="SELECT * FROM $tbl_name";

$result=mysql_query($sql);

$count=mysql_num_rows($result);

//Provide the user with the number of articles in the database

//space string

$counttxt = "There are";

echo $counttxt;

print_r($count); $print = print 'articles in this database';

echo $print;

?>

<table width="400" border="0" cellspacing="1" cellpadding="0">

<tr>

<td><form name="form1" method="post" action="">

<table width="900" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">

<tr>

<td bgcolor="#FFFFFF"> </td>

<td colspan="4" bgcolor="#FFFFFF"><strong>Select the articles you would like delete.</strong> </td>

</tr>

<tr>

<td align="center" bgcolor="#FFFFFF">#</td>

<td align="center" bgcolor="#FFFFFF"><strong>ID</strong></td>

<td align="center" bgcolor="#FFFFFF"><strong>Title</strong></td>

<td align="center" bgcolor="#FFFFFF"><strong>Content</strong></td>

<td align="center" bgcolor="#FFFFFF"><strong>Frontpage</strong></td>

</tr>

<?php

while($rows=mysql_fetch_array($result)){

?>

<tr>

<td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['articleID']; ?>"></td>

<td bgcolor="#FFFFFF"><? echo $rows['articleID']; ?></td>

<td bgcolor="#FFFFFF"><? echo $rows['title']; ?></td>

<td bgcolor="#FFFFFF"><? echo $rows['content']; ?></td>

<td bgcolor="#FFFFFF"><? echo $rows['frontpage']; ?></td>

</tr>

<?php

}

?>

<tr>

<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>

</tr>

<?

//set the delete variable

$delete = (isset($_POST['checkbox']));

//use isset to check if the variable has been set or not

if ($delete){

$sql = "DELETE FROM $tbl_name WHERE id='$del_id'";

$result = mysql_query($sql);

echo 'You are deleting this article';

print_r($result);

// Check if delete button active, start this

for($i=0;$i<$count;$i++){

$del_id = $checkbox[$i];

//print out the checkbox

}

// if successful redirect to delete_multiple.php

if($result){

echo 'You have deleted the article(s)';

//echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete_multiple.php\">";

}

}

//mysql_close();

?>

</table>

</form>

</td>

</tr>

</table>

articles_list.phpFetching info...

Link to comment
https://www.neowin.net/forum/topic/1065264-php-check-box-delete-script/
Share on other sites

13 answers to this question

Recommended Posts

  • 0

off the top of my head you might need to change input name="checkbox[]" to input name="checkbox".

You probably also need to put the entire table inside 'form' tags which state where the submit button will post to.

I mean you probably need to state where the form will post to so something like <form name="form1" method="post" action="<?php $_SERVER['PHP_SELF'] ?>">

EDIT:

also change this: $sql = "DELETE FROM $tbl_name WHERE id='$del_id'";

to this: $sql = "DELETE FROM $tbl_name WHERE id='$delete'";

EDIT2:

Your also forgot an apostrophe on line 50.

This one works fine: http://pastebin.com/smsde5Z8

You will need to sanitize the table checkbox inputs with mysql_escape_string or something otherwise people could put anything in there and submit it - and kindly drop all your data for you!

See here: http://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php

  • 0

Sorry to disturb you but I have one more quesiton I've set the variable to the input name but it only deletes the record with an ID of 1 all the time.

<?php

//include database

require_once('db_config.php');

$tbl_name="articles"; // Table name

$sql="SELECT * FROM $tbl_name ORDER BY articleID";

$result=mysql_query($sql);

$count=mysql_num_rows($result);

//Provide the user with the number of articles in the database

echo "There are ".$count." articles in this database";

?>

<table width="400" border="0" cellspacing="1" cellpadding="0">

<tr>

<td><form name="form1" method="post" action="">

<table width="900" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">

<tr>

<td bgcolor="#FFFFFF"> </td>

<td colspan="4" bgcolor="#FFFFFF"><strong>Select the articles you would like delete.</strong> </td>

</tr>

<tr>

<td align="center" bgcolor="#FFFFFF">#</td>

<td align="center" bgcolor="#FFFFFF"><strong>ID</strong></td>

<td align="center" bgcolor="#FFFFFF"><strong>Title</strong></td>

<td align="center" bgcolor="#FFFFFF"><strong>Content</strong></td>

<td align="center" bgcolor="#FFFFFF"><strong>Frontpage</strong></td>

</tr>

<?php

while($rows=mysql_fetch_array($result)){

?>

<tr>

<td align="center" bgcolor="#FFFFFF"><input name="checkbox" type="checkbox" id="checkbox" value="<? echo $rows['articleID']; ?>"></td>

<td bgcolor="#FFFFFF"><? echo $rows['articleID']; ?></td>

<td bgcolor="#FFFFFF"><? echo $rows['title']; ?></td>

<td bgcolor="#FFFFFF"><? echo $rows['content']; ?></td>

<td bgcolor="#FFFFFF"><? echo $rows['frontpage']; ?></td>

</tr>

<?php

}

?>

<tr>

<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>

</tr>

<?

//set the delete variable

$del_id = (isset($_POST['checkbox']));

//use isset to check if the variable has been set or not

if ($del_id){

$sql = "DELETE FROM $tbl_name WHERE articleID='".$del_id."'";

echo $sql;

$result = mysql_query($sql);

//$art_del = "You are deleting this article";

//echo ".$art_del.";

print_r($result);

// Check if delete button active, start this

for($i=0;$i<$count;$i++){

$del_id = $checkbox[$i];

//print out the checkbox

}

// if successful redirect to delete_multiple.php

if($result){

//echo 'You have deleted the article(s)';

//echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete_multiple.php\">";

}

}

//mysql_close();

?>

</table>

</form>

</td>

</tr>

</table>

  • 0

The reason it is only deleteing one, is because you arn't looping through your SQL to delete the article ID's for each id. The difference of checkbox[] and checkbox as the above people have mentioned to be changed. You were right with sending it as "name=checkbox[]". Because then php interrupts the post data as a array. And thats what you would want. By using "name=checkbox" with multiple id's only one id is being sent back.

  • 0
  On 20/03/2012 at 19:35, mallenium115 said:

Thank you so once I revert back to checkbox[] it should work normally, how about the logic and structure of the form is everything alright so far?

Once you revert checkbox back to checkbox[], php will see the post data with the article ids as a $_POST[checkbox] array. Then you need to modify your DELETE sql to do a FOREACH $_POST[checkbox] to delete each ID and execute each SQL. There are cleaner ways to use a DELETE sql with only 1 sql. But as a learning experience, get with what you need working first. Then optimize later.

I'd modify you're code but i'm not fond of diving in. Id rather re-write it all or explain it to you how to re-write it lol.

  • 0
  On 20/03/2012 at 19:52, mallenium115 said:

I'd prefer the explaination so I can learn more. Thank you for the help I truly appreciate the support. I'm new at complex php scripting, basically creating an CMS for my internship. can you give me an example of the sql to work from?


<?php
// Check if Post Data was Sent, else just echo out a Form to the Viewer. If post was sent $_POST is valid and don't echo out a form.
if (!$_POST) {
echo "<form method=\"post\">";
echo "<input type=\"checkbox\" name=\"checkbox[]\" value=\"001\">Value 1<br/>";
echo "<input type=\"checkbox\" name=\"checkbox[]\" value=\"002\">Value 2<br/>";
echo "<input type=\"checkbox\" name=\"checkbox[]\" value=\"003\">Value 3<br/>";
echo "<input type=\"submit\" value=\"Submit\">";
}
else {
// See if checkbox[] Data is in POST Data and has Values, if so Continue.
if (count($_POST[checkbox]) != 0) {
// Lets loop through each checkbox[] value and preform a DELETE on it.
foreach ($_POST[checkbox] as $key => $value) {
// Here we check our field if its valid, this is a simple charecter type check. We Verify its a digit.
if (ctype_digit($value)) {
$sql = "DELETE FROM $tbl_name WHERE articleID=$value";
// mysql_query($sql);
// Print out that a query was executed for the assoicated articleID.
echo "articleID=$value" . ": Executed Query.<br/>";
}
else {
// We should kill the script, invalid non digit data was sent in the form.
die("Invalid Data Sent.");
}
}
echo "Finished Deleteing Articles from Form.";
}
}
?>
[/CODE]

I commented out the mysql_query part just because I don't have a database to test against and what not. But that gives you a idea of what i'm talking about. Feel free to PM some messenger (aim etc) details I don't mind answering a q for someone once and awhile :).

Also missing from this is db_config and $tbl_name. Heh.

  • 0

Okay so in my case what would I set my checkbox value to for the POST?

if (!$_POST) {

echo "<form method=\"post\">";

echo "<input type=\"checkbox\" name=\"checkbox[]\" value=\"001\">Value 1<br/>";

}

<tr>

<td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['articleID']; ?>"></td>

<td bgcolor="#FFFFFF"><? echo $rows['articleID']; ?></td>

<td bgcolor="#FFFFFF"><? echo $rows['title']; ?></td>

<td bgcolor="#FFFFFF"><? echo $rows['content']; ?></td>

<td bgcolor="#FFFFFF"><? echo $rows['frontpage']; ?></td>

</tr>

<?php

}

?>

<tr>

<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>

</tr>

<?

?>

This topic is now closed to further replies.
  • Posts

    • LG Electronics sees profit dip but boosts shareholder returns by Paul Hill LG Electronics (LGE) has reported consolidated sales of 20.74 trillion Korean Won (approximately $15.14 billion USD) and an operating profit of 639.4 billion Korean Won (approximately $466.75 million USD) for the second quarter of 2025. The firm saw both its revenue and operating profits decline year-over-year due to external factors such as US tariff policies, ongoing geopolitical issues in the Middle East, and a slowdown in consumer spending. While the company has faced challenges, the company is aiming for what it called qualitative growth by strengthening its subscription services, direct online sales, and business-to-business (B2B) segments. Key areas of growth for LGE include automotive electronics, heating, ventilation, and air conditioning (HVAC) systems, and the webOS platform. The US tariffs are a major headache for companies around the world, given the size of the market there and President Trump's demands for bringing manufacturing to the States. To combat the rising US tariffs, LGE is trying to optimize global production and refine its market-specific approaches for premium and mass-market products. While the company’s profits dipped, it announced an interim dividend of 500 Korean Won (approximately $0.37 USD) per share for both common and preferred, with another payout later in the year that should take the total for 2025 to at least 1,000 Korean Won (approximately $0.73 USD). You must be holding the stock on August 8, 2025, to get the payout on August 22, 2025. The firm also said it will cancel 761,427 common treasury shares on July 31, 2025, making shares more scarce which could increase the value of remaining shares for investors. In terms of LGE’s various business divisions, things were mixed. Its Home Appliance Solution (HS) business achieved year-over-year sales growth, maintaining profitability, thanks to a dual strategy for premium and volume segments and growth in online sales and subscriptions. Its Media Entertainment Solution (MS) business experienced declines in sales and operating profits with the latter turning negative due to market uncertainties and stiff competition. Its Vehicle Solution (VS) business showed growth in sales and operating profit thanks to increased orders from European automotive makers. Finally, its Eco Solution (ES) business saw domestic sales increase, but overseas sales growth was limited due to US tariffs. This led to a slight year-over-year drop in operating profit due to higher costs. Image via Depositphotos.com
    • "Microsoft plans to remove the MSN feed..." Yaaay, finally the horrible dumpster fire of badly translated tabloid trash is going away! Good riddance! "...and replace it with Copilot Discover..." Oh ffs...
    • Similar to how Nvidia stopped caring about the consumer market a while ago and now just pays lip service to it because it prints money.
    • Yep same as every company, sadly. The biggest bank in Australia just laid off a bunch of staff even though they made record profits, then advertised the roles in India
  • Recent Achievements

    • Week One Done
      Itbob513626 earned a badge
      Week One Done
    • One Month Later
      Itbob513626 earned a badge
      One Month Later
    • Rookie
      EdwardFranciscoVilla went up a rank
      Rookie
    • Week One Done
      MoJo624 earned a badge
      Week One Done
    • Collaborator
      aeganwn earned a badge
      Collaborator
  • Popular Contributors

    1. 1
      +primortal
      618
    2. 2
      ATLien_0
      243
    3. 3
      Xenon
      159
    4. 4
      Michael Scrip
      126
    5. 5
      +FloatingFatMan
      122
  • Tell a friend

    Love Neowin? Tell a friend!