Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single PHP form with 2 (edit and delete) buttons

I am trying to set up a form with 2 buttons - "DELETE" which runs on the page delete.php and "EDIT" which runs on edit.php.

So I need a different action depending on which button they have clicked...

Here's my code.

$con = mysql_connect("localhost","user","password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test", $con);

$result = mysql_query("SELECT * FROM myTable");

// Need to change the action depending on what button is clicked
echo "<form name='wer' id='wer' action='delete.php' method='post' >";
echo "<table border='1'>";

while($row = mysql_fetch_array($result))
  {
    echo "<tr>";
    echo "<td>" . $row['id'] . "</td>";
    echo "<td>" . $row['page_title'] . "</td>";
    echo "<td><input type='radio' name='test1' value='" . $row['id'] . "' /></td>";
    echo "</tr>";
  }

echo "<tr>";
echo "<td>&nbsp;</td>";
echo "<td>&nbsp;</td>";
echo "<td><input type='submit' name='delete' value='Delete' /> <input type='submit' name='edit' value='Edit' /></td>";
echo "</tr>";
echo "</table>";
echo "</form>";

mysql_close($con);
like image 952
Tom Avatar asked Dec 28 '22 20:12

Tom


2 Answers

You could do that with JavaScript:

<input type='button' value='Delete' onclick='
    this.form.action = "delete.php";
    this.form.submit();
' />

Or you can do it with PHP, by having the form action be, say, action.php, which would contain:

if (!empty($_REQUEST['delete'])) {
    require_once dirname(__FILE__) . '/delete.php';
else if (!empty($_REQUEST['edit'])) {
    require_once dirname(__FILE__) . '/edit.php';
}
like image 149
rid Avatar answered Dec 30 '22 11:12

rid


Check for isset($_POST['delete']) and isset($_POST['edit']).

However, it's a bad idea to have the delete button first. When pressing the ENTER key, browsers usually use the first button - and pressing enter in a form should not delete stuff.

like image 21
ThiefMaster Avatar answered Dec 30 '22 09:12

ThiefMaster