简体   繁体   中英

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);

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.

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';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM