我有一个代码,应该通过使用SQL查询加载remove.php文件来从表中删除选定的ID行。问题是它不起作用,但是我没有收到任何错误或通知。我的变量似乎可以传送到URL中的remove.php,因为'<a href="remove.php?='.$Fvalue.'">'
被解释为
remove.php?= 1
例如,其中1是该行的主要ID。
这里仅是与问题相关的所有代码:
编辑:
带有“删除”按钮的产品表的呈现的HTML:
<!-- Products table -->
<table class="table">
<thead>
<tr>
<th scope='col'>id </br ></th><th scope='col'>name </br ></th><th scope='col'>price </br ></th><th scope='col'>amount </br ></th><th scope='col'>category_name </br ></th> </tr>
</thead>
<tbody>
<tr><td data-id="1"><a href="remove.php?remove_id=1"> REMOVE</a></td>
<td>iPhone 7</td>
<td>800</td>
<td>15</td>
<td>Smartphones</td>
</tr><tr>
<td data-id="42"><a href="remove.php?remove_id=42"> REMOVE</a></td>
<td>Motorola </td>
<td>3000</td>
<td>5</td>
<td>Smartphones</td>
</tr><tr><td data-id="2"><a href="remove.php?remove_id=2"> REMOVE</a></td><td>Macbook Pro 2015</td>
<td>1300</td><td>10</td>
<td>Computers</td></tr><tr><td data-id="4"><a href="remove.php?remove_id=4"> REMOVE</a></td>
<td>Dell XPS</td>
<td>1400</td>
<td>6</td><td>Computers</td>
</tr><tr><td data-id="41"><a href="remove.php?remove_id=41"> REMOVE</a></td>
<td>CHROMEBOOK</td>
<td>5600</td>
<td>8</td>
<td>Computers</td></tr></tbody>
更新的PHP:
<?php
foreach ($newArray as $value) {
echo '<tr>';
foreach ($value as $key => $Fvalue) {
$remove = $value['id'] = " REMOVE";
if($value[$key] == $value['id']) {
echo '<td data-id="'.$Fvalue.'">' . '<a href="remove.php?remove_id='.$Fvalue.'">' . $remove . '</a>' . '</td>'; // will show all values.
} else {
echo '<td>' . $Fvalue . '</td>';
}
}
echo '</tr>';
}
?>
remove.php
<?php
require_once ("navigation.php");
require_once("database_connection.php");
$id = !empty($_GET['remove_id']) ? $_GET['remove_id'] : null;
if($id != null) {
$deleteProducts = "DELETE FROM `products` WHERE `id` = '.$id.'";
mysqli_query($dbc, $deleteProducts);
}
正在寻找任何对我有帮助的问题,因为我没有收到任何错误,也不知道为什么代码没有删除表中的一行。谢谢。
答案 0 :(得分:3)
您必须传递与您要发送的值关联的密钥;
<a href="remove.php?remove_id='.$Fvalue.'">' . $remove . '</a>
注意remove_id
部分。
现在,在您的PHP中,您可以获取该值;
$id = !empty($_GET['remove_id']) ? $_GET['remove_id'] : null;
if($id !== null) {
$deleteProducts = "DELETE FROM `products` WHERE `id`='{$id}'";
mysqli_query($dbc, $deleteProducts);
}
在这里的代码中,我还解决了您在代码中遇到的问题。您有$id = (isset($_GET['$Fvalue']));
,它将始终将$id
设置为true
或false
,而不是您传递的ID。
您还可以使用双引号而不是单引号来清理HTML变量。
if($value[$key] == $value['id']) {
echo "<td data-id='{$Fvalue}'><a href='remove.php?remove_id={$Fvalue}'>{$remove}</a></td>"; // will show all values.
} else {
echo "<td>{$Fvalue}</td>";
}
大注: Little Bobby说you may be at risk for SQL Injection Attacks。通过Prepared Statements了解parameterized queries。
答案 1 :(得分:0)
使用get方法,您的网址中需要键/值对。
remove.php?id=1
其中id是键,而1是值。