单个PHP表单,带有2个(编辑和删除)按钮

时间:2011-05-23 14:42:19

标签: php forms form-submit

我正在尝试设置一个带有2个按钮的表单 - “DELETE”在delete.php页面上运行,“EDIT”在edit.php上运行。

所以我需要一个不同的动作,具体取决于他们点击了哪个按钮......

这是我的代码。

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

2 个答案:

答案 0 :(得分:5)

检查isset($_POST['delete'])isset($_POST['edit'])

然而,首先拥有删除按钮是一个糟糕的想法。当按下 ENTER 键时,浏览器通常会使用第一个按钮 - 并且在表单中按Enter键不应删除内容。

答案 1 :(得分:5)

你可以用JavaScript做到这一点:

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

或者你可以使用PHP,通过表单操作,例如,action.php,它将包含:

if (!empty($_REQUEST['delete'])) {
    require_once dirname(__FILE__) . '/delete.php';
else if (!empty($_REQUEST['edit'])) {
    require_once dirname(__FILE__) . '/edit.php';
}