我正在尝试在项目表上添加“删除”按钮,并有一个删除按钮来删除项目以及有关项目和卖家的信息。我在桌面上有删除按钮,但我无法弄清楚如何在单击时处理该按钮。请帮忙!提前谢谢!!
<?php
require 'authentication.inc';
// connect to the server
$connection = sqlsrv_connect( $hostName, $connectionInfo )
or die("ERROR: selecting database server failed");
// prepare SQL query
$UserID = $_SESSION['userID'];
$query = "SELECT * FROM ITEM WHERE userID= '$UserID'";
// Execute SQL query
$query_result = sqlsrv_query($connection, $query)
or die( "ERROR: Query is wrong");
// Output query results: HTML table
echo "<table border=1>";
echo "<tr>";
// fetch attribute names
foreach( sqlsrv_field_metadata($query_result) as $fieldMetadata)
echo "<th>".$fieldMetadata['Name']."</th>";
echo "</tr>";
// fetch table records
while ($line = sqlsrv_fetch_array($query_result, SQLSRV_FETCH_ASSOC)) {
echo "<tr>\n";
foreach ($line as $cell) {
echo "<td> $cell </td>";
}
echo "<td></td>";
echo "</tr>\n";
}
echo "</table>";
// close the connection with database
sqlsrv_close($connection);
?>
答案 0 :(得分:0)
要添加删除功能,您需要两件事,一个按钮,其次是处理所述按钮。我不确定表中的唯一值是什么,所以我使用的是这个虚构的密钥:itemID
。使用您唯一的列名更新。
将表循环替换为:
<table border=1>
<tr>
<?php
// fetch attribute names
foreach( sqlsrv_field_metadata($query_result) as $fieldMetadata)
echo "<th>".$fieldMetadata['Name']."</th>"; ?>
</tr>
<?php
// fetch table records
while ($line = sqlsrv_fetch_array($query_result, SQLSRV_FETCH_ASSOC)) { ?>
<tr>
<?php foreach ($line as $cell) {
echo "<td> $cell </td>";
} ?>
<td>
<form method="post">
<input type="hidden" name="itemID" value="<?php echo $line['itemID']; ?>" />
<input type="submit" name="action" value="DELETE" />
</form>
</td>
</tr>
<?php } ?>
</table>
在顶部的处理部分,添加处理:
if(!empty($_POST['action']) && ($_POST['action'] == 'DELETE')) {
// Do some sort of validation here
if(is_numeric($_POST['itemID']))
sqlsrv_query($connection, "delete from ITEM where itemID = '".$_POST['itemID']."'");
}