我有一个数据表,我想允许用户通过单击表中的链接从中删除行。我希望刷新页面并从表中删除用户选择的行。这是基于调用更改表数据库的 php 函数来完成的。到目前为止,我所拥有的是
<tr>
<td width = '35%'><?php echo $the_title?></td>
<td width = '20%'><?php echo $val1?></td>
<td width = '10%'><?php echo $val2 ?></td>
<td width = '15%'><a href='?remove_now=<?php echo $row?>' name=''>Remove Now</a></td>
</tr>
<?php
if (isset($_GET['remove_now'])){
$row_to_remove=$_GET['remove_now'];
my_func ($row_to_remove);}
?>
当我单击"立即删除"链接时,它会更改页面,因为我已经在哈希页面上,我不希望它这样做。它也不会my_func运行。有什么想法吗?谢谢
服务器端运行,页面更新在客户端(浏览器)上运行。如果要执行php代码,则必须刷新页面,或者需要使用javascript ajax调用,该调用将实际访问您要查找的服务器上的"页面",获取其数据,并将其提供给当前页面(进行ajax调用)。
如果你只想操作页面,不需要来自服务器的任何数据,只需使用 javascript。Javascript是用于dom操作的,而不是php。
好吧,你不能用php做你想做的事情。 你需要使用javascript来做你想做的事。
这里有一些方法可以完成你想要的
1)使用JavaScript操作页面上已经呈现的表格
或
2) 使用 PHP 在页面初始加载时呈现没有所需行的表格
如果您需要使用 PHP 作为行删除过程的一部分,您应该研究 Ajax。
根据您的评论,尝试这样的事情:
<tr>
<td width = '35%'><?php echo $the_title?></td>
<td width = '20%'><?php echo $val1?></td>
<td width = '10%'><?php echo $val2 ?></td>
<?php
$maxnumrows = 10;
for($i=0;$i<$maxnumrows;$i++){
if ( (!isset($_GET['remove_now'])) || ( (isset($_GET['remove_now'])) && ($_GET['remove_now']!=$i) ) ){
?>
<td width = '15%'><a href='?remove_now='<?php echo $i?> name=''>Remove Now</a> </td>
<?php
}
}
?>
</tr>
href 属性上的结束引号是错误的。它应该是在像这样关闭 php 标签之后。
<td width = '15%'><a href='?remove_now=<?php echo $row?>' name=''>Remove Now</a></td>
是的.. javascript和ajax也可以工作,只需单击链接并显示相同的页面。如果您不希望更改网址,请在my_func调用后放入header("Location ....")
干杯
听起来您正在尝试从数据库中删除条目,而您只是在向后思考。下面是一个简化的逻辑,可以帮助您了解如何执行此操作:
// See if they just deleted something
// If so we will delete the data and reload the page
if(isset($_GET['delete_id']))){
// Run the code that deletes the entry from the database
deleteFromDatabase($_GET['delete_id']);
// Now that we've done that just cleanly reload the page
header('Location: '.$_SERVER['PHP_SELF']); // This refers to the current page without the $_GET query string - there must not be any page output before you call this
die(); // Always kill the script after reloading the location header
}
// Here's your normal output (whatever you would normally do for output)
getTableData();
outputTable();
echo '<table>Whatever etc...';
?>