Friday, August 17, 2012

Handling Mutiple Selections In PHP

Hello there

this is my firs post, hopefully it will be useful and the blog overall will be a good reference to all developers

this post is about how to handle multiple selections in the same form like delete multiple emails or applying an action to multiple items

usually most of developers handle each item alone, like a delete button beside each email but what if you wanted to handle all the items once together

here is the solution for doing that

consider we have a table called "items" contains items data with a unique ID field

CREATE TABLE IF NOT EXISTS `items` (
  `ItemId` int(11) NOT NULL AUTO_INCREMENT,
  `ItemName` varchar(30) NOT NULL,
  PRIMARY KEY (`ItemId`)
)

I am going to use a usual query to read the data from the table

<?php

mysql_connect("localhost", "root", "");

mysql_select_db("test");

$query = "SELECT ItemId, ItemName FROM items";

$result = mysql_query($query);

?>

<form method="post" action="page.php">

<table border="1">
<tr>
    <td>#</td>
    <td>Item Name</td>
</tr>
<?php

while ($row = mysql_fetch_assoc($result)){
    echo "<tr>";
    echo "<td>";
    echo "<input type=\"checkbox\" name=\"Items[]\" value=\"" . $row['ItemId'] . "\"/>";
    echo "</td>";
    echo "<td>";
    echo $row['ItemName'];
    echo "</td>";
    echo "</tr>";   
}

?>
</table>
<input type="submit" name="delete" value="Delete" />
</form>

The magic goes here

echo "<input type=\"checkbox\" name=\"Items[]\" value=\"" . $row['ItemId'] . "\"/>";

when you name all the checkboxes the same name with [] after it the php will consider it ass an array and give each selected item a index in the array with the ItemId as its value

if I selected item number 1 and 2 the Items array will contain two items with the value of there ItemId's

output preview





And now I will add a piece of code to handle the delete button

if ($_POST['delete']) {

    $ids = join(",", $_POST['Items']);

    mysql_query("DELETE FROM items WHERE ItemId IN (" . $ids . ")");

    echo count($_POST['Items']) . " Items Has Been Deleted";
}

The whole code will be

<?php

mysql_connect("localhost", "root", "");

mysql_select_db("test");

if ($_POST['delete']) {

    $ids = join(",", $_POST['Items']);

    mysql_query("DELETE FROM items WHERE ItemId IN (" . $ids . ")");

    echo count($_POST['Items']) . " Items Has Been Deleted";
}


$query = "SELECT ItemId, ItemName FROM items";

$result = mysql_query($query);

?>

<form method="post" action="page.php">

<table border="1">
<tr>
    <td>#</td>
    <td>Item Name</td>
</tr>
<?php

while ($row = mysql_fetch_assoc($result)) {
    echo "<tr>";
    echo "<td>";
    echo "<input type=\"checkbox\" name=\"Items[]\" value=\"" . $row['ItemId'] . "\"/>";
    echo "</td>";
    echo "<td>";
    echo $row['ItemName'];
    echo "</td>";
    echo "</tr>";
}

?>
</table>
<input type="submit" name="delete" value="Delete" />
</from>

No comments:

Post a Comment