Question

I have a database table for my "Services" which contains a serviceid and some other non-related fields. I am using PHP to dynamically generate an HTML table that displays the queried services. In each of the rows is a corresponding "View" button that when clicked should submit to the same page with the value of the id of the service to be viewed (the page will then redirect to another page after setting $_POST['serviceid'] equal to the value passed from the button).

Here is how I am dynamically creating my HTML table with PHP:

    while(list($id, $name, $details, $datecreated, $firstname, $lastname) = $results->fetch_row())
    {
      if($index % 2 == 0)
      {
        echo "<tr BGCOLOR=\"#DCDCDC\" style=\"color: Black;\">";
      }
      else
      {
        echo "<tr>";
      }
      echo "<td>" . "<input type=\"checkbox\" id=\"flag$id \" name=\"flag\" value=\"Flag$id\"/>" . "</td>";
      echo "<td>" . "<input type=\"submit\" id=\"view$id \" name=\"view\" value=\"View\"/>" . "</td>";
      echo "<td>" . $id . "</td>";
      echo "<td>" . $name . "</td>";
      echo "<td>" . $details . "</td>";
      echo "<td>" . $datecreated . "</td>";
      echo "<td>" . $firstname . " " . $lastname . "</td>";
      echo "</tr>";

      $index++;
    } 

This is my results.view.php, this is where I display the data. While you can't see the <form> tag above it is sufficient to know that it posts back to the controller that includes this view and the model that handles the button presses and whatnot.

My question then is how do I know which view button is being clicked? It could be on the first service, the last one, or any in between. I have placed the $id of the service in the id value of the button, but I am unsure how to reference that. If I knew how to do that, then I could potentially splice out the word "view" and would be left with the id needed to perform the task.

Any ideas?

Was it helpful?

Solution

Only the the value of button you've clicked will be sent to the next page. If you assign all the buttons unique names, you can then simply check for them with

if (isset($_POST['button1'])) echo "button 1 was clicked";.

Of course this won't work if you submit the form with [Enter] in one of the fields. Another option would be to use a radio button for this? Or more forms.

OTHER TIPS

Giving your buttons àn ID will solve mouse issues, but it will not work with keyboards; The first submit button will declare itself pressed no matter of where your key focus is.

There is 2 solutions as I can see it:

  • use A elements instead, with an query-string.
  • a FORM element in every TR.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top