tags:

views:

44

answers:

3

Hello,

In Php as we all know, there are no inbuilt controls by itself like Asp.Net's GridView etc. I am using Html's <table> to build up the grid and keep the row's id in one hidden field. I've also placed one checkbox at the beginning of each row and a delete button at the bottom of the grid. The problem i face is, how do i get all the id's that are checked so that i can pass those ids in my IN clause of Delete?

+1  A: 

First you name all your checkboxes by suffixing [] in their name so that an array gets created, later this is how you can get those that are checked and act accordingly:

for($i = 0; $i < count($_POST['checks']); $i++)
{
  if (isset($_POST['checks'][$i]))
  {
     // this was checked !!
  }
}

Where checks is the name of all those checkboxes eg:

<input type="checkbox" name="checks[]" value="1" />
<input type="checkbox" name="checks[]" value="2" />
<input type="checkbox" name="checks[]" value="3" />

And this is how you can get those for your IN clause in your query:

$checked_array = array();

for($i = 0; $i < count($_POST['checks']); $i++)
{
  if (isset($_POST['checks'][$i]))
  {
     $checked_array[] = mysql_real_escape_string($_POST['checks'][$i]);
  }
}

// build comma separated string out of the array
$values = implode(',', $checked_array);

Now you can use the $values in your IN clause of your query.

Sarfraz
You duplicated $_POST['checks'] to $checked_array? IMO He can't use an array in his query directly :o
fabrik
Yeah, this won't work. Plus, it's quite vulnerable to SQL injection.
ceejayoz
$IN = implode(',', $checked_array);
fabrik
@fabrik: It is not duplicated, the `$checked_array` only contains checked checkboxes. Also later on, a comman separates each value therefore it can be used in the IN clause.
Sarfraz
That was why i wrote that the values need to be added between []'s. In that case you'll getting only submitted boxes.
fabrik
+1  A: 

Take a look at what is currently being submitted:

var_dump($_POST);

You will see all of the field values. If you do the checkboxes right, you'll have an array of rowID's to delete, and you can simply implode(',',$_POST['checkBoxes']) or something similar when building your query.

Security would be a concern here... I'm sure someone else will post in depth about that, but you definitely want to validate that the user can delete these records.

Fosco
+1  A: 

Name every checkbox with a semi-unique name like tablerow[numeric_id]. When you submit the form you can simply catch all posted tablerow value that was checked.

fabrik