如何在PHP中编辑/删除数据库中存储的数据


How To Edit/Delete Stored Data From Database In PHP

编辑

我有一个mysql表,其中的字段如下:

产品-序列号、名称、描述、价格、图片。

viewproducts.php页面如下所示:

    <?php
$result = mysql_query("SELECT * FROM products ")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
       echo 'There Arent Any Products';
    } else {
echo "<table border='0'><table border='1' width=100%><tr><th>Product Name</th><th>Description</th><th>Price</th><th>Image</th><th>Edit</th><th>Delete</th>";
while($info = mysql_fetch_array($result))
{
        echo "<tr>";
        echo "<td>" . $info['name']. "</td>";
        echo "<td>" . $info['description']. "</td>";
        echo "<td>£" .  $info['price']." </td>";
        echo "<td>" . "<img src='../getImage.php?id=" . $info['serial'] ."'/></td>";
        echo '<td> <a href="edit.php?product_id="' . $info['serial'] . '">Edit</a></td>';
}
    }
echo "</tr>";
echo "</table>";
?>

我的edit.php页面如下:

 <?php
$product_id = $_GET['serial'];
$result = mysql_query("SELECT * FROM products WHERE serial = '$product_id'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
       echo 'There Arent Any Products';
    } else {
echo "<table border='0'><table border='1' width=100%><tr><th>Product Name</th><th>Description</th><th>Price</th><th>Image</th><th>Edit</th><th>Delete</th>";
while($info = mysql_fetch_array($result))
{
        echo "<tr>";
        echo "<td>" . $info['name']. "</td>";
        echo "<td>" . $info['description']. "</td>";
        echo "<td>£" .  $info['price']." </td>";
        echo "<td>" . "<img src='../getImage.php?id=" . $info['serial'] ."'/></td>";
}
    }
echo "</tr>";
echo "</table>";
?>

当我从thrviewproducts.php页面点击edit时,它会转到edit.php页面,在那里什么都没有显示。地址栏上的序列号如下所示:

 http://www.********.com/****/admin/edit.php?product_id=

我希望能够编辑从viewproduct.php页面点击并转移到edit.php页面的任何产品。我认为我的edit.php页面设置不正确。

请帮忙,

感谢

您可以通过$_GET传递产品的id,然后在编辑/删除页面中检索该参数。显然,在使用之前,您必须正确地对输入进行消毒。例如,每个产品的链接应该如下所示:

echo '<td><a href="edit.php?id="' . $info['id'] . '">Edit</a></td>';

在编辑页面中,你应该有这样的东西:

$id = $_GET['id'];
// For example, if the product id is an integer
// you can sanitize it doing this
$id = (int) $id

您可以将其作为参数传递到您想要编辑/删除产品的php文件:

<a href="edit.php?product_id=<?php echo $row['product_id']; ?>">Edit Product</a>

然后在edit.php中,您将获取产品的id并从数据库中加载它的数据。

[edit.php]
$product_id = isset($_GET['product_id']) ? intval($_GET['product_id']) : null;
if(!$product_id) {
    exit();
}
// query your database for the product
$row = mysqli_query("SELECT * FROM <table> WHERE product_id = $product_id");
// then you output your html with fields populated from the result from the database