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

时间:2011-11-23 22:42:23

标签: php mysql database error-handling

修改

我有一个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>";
?>

当我从thr viewproducts.php页面点击编辑时,它会转到edit.php页面,其中没有任何内容显示。地址栏上的序列ID如下:

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

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

请帮忙,

由于

2 个答案:

答案 0 :(得分:0)

您可以通过$_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

答案 1 :(得分:0)

你可以将它作为参数传递给你想要编辑/删除产品的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