PHP URL重写链接

时间:2011-04-12 12:11:20

标签: php

我在表格中删除了每行的链接。 当我单击该链接时,我将id传递给使用该ID删除该行的页面。 我的网址的最后一部分看起来像delete_row.php?id = 5 我可以只显示delete_row.php而不显示?id = 5

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
     function redirect(URL)
     {
       document.location="delete_row.php";
       return false;
     }
</script>
</head>

<body>
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("test", $con);

$result = mysql_query("SELECT * FROM users");
?>
<table border="1">
<th>Name</th>
<th>Age</th>
<th>&nbsp;</th>
<?php 
while($row = mysql_fetch_array($result))
  {?>
  <tr>
  <td><?php echo $row['name'];?></td>
  <td><?php echo $row['age'];?></td>
  <td><a href="javascript:" onclick="return redirect('delete_row.php?id=<?php echo $row['id']; ?>');">Delete</a></td>
  </tr>
  <?php } ?>
</table>
<?php
mysql_close($con);
?>
</body>
</html>

这是文件名为delete_row.php的

的PHP部分
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("test", $con);
if(isset($_REQUEST['id']))
$id = $_REQUEST['id'];
mysql_query("DELETE FROM users WHERE id='$id'");
mysql_close($con);
?> 

我得到的错误是 注意:未定义的变量:第13行的C:\ MYXAMPP \ delete_row.php中的id

4 个答案:

答案 0 :(得分:0)

这对你有用吗?

<a href="delete_row.php" onclick="this.href = this.href + '?id=5'">Delete</a>

你也可以这样做:

<script language="javascript" type="text/javascript">
     function redirect(URL)
     {
       if(confirm('Are you sure you wish to delete this item?'))
           document.location=URL;
       return false;
     }
</script>
<a href="javascript:" onclick="return redirect('delete_row.php?id=5');">Delete</a>

答案 1 :(得分:0)

页面如何知道要删除哪一行?你必须向它发送某种标识符。如果你的意思是,在删除之后,再次隐藏ID,你可以通过使用重定向来实现:

header('Location:urlOfPageWithoutQueryString');

答案 2 :(得分:0)

您可以使用小表单,“删除”按钮是提交按钮。将方法设置为“发布”。一个例子:

<form action="delete_row.php" method="post">
  <input type="hidden" name="row" value="5">
  <input type="submit" value="Delete">
</form>

在PHP文件中,您可以使用POST值而不是GET值。这也是正确的 - GET动作应该是幂等的(即除了返回所请求的信息之外应该没有任何效果)。

答案 3 :(得分:0)

你不应该像GET is considered as being a safe method那样使用GET进行这种行动:

  

[...]已经建立了GET和GET的公约      HEAD方法不应该具有采取行动的意义      除了检索。这些方法应该被认为是“安全的”。

使用POST表单,您可以使用隐藏的表单控件来识别ID:

<form action="delete_row.php" method="post">
    <input type="hidden" name="id" value="5">
    <input type="submit" value="Delete row">
</form>

除了安全方法之外,使用POST代替GET也不容易受到Cross-Site Request Forgery attacks的攻击。此时,您还应该考虑使用所谓的CSRF令牌来进一步降低CSRF攻击成功的可能性。