php - 安全地传递 id 来更新表?
问题描述
我想用用户添加的产品数量更新一个表。
我首先在表中选择所有具有相同代码的产品,并在输入名称中写有id(在表中)。
客户端:
<input name="<?php echo $product['id']; ?>" type="number" min="1" placeholder="Quantity" required/>
服务器端:
<?php
session_start();
require __DIR__."/../connectDB.php";
$memberId = $_SESSION['user_id'];
foreach ($_POST as $prodId => $quantity) {
$stmt =$conn->prepare("UPDATE tbl_product SET stock = ? WHERE id = ? AND member_id = ?");
$stmt->bind_param("iii", $quantity, $prodId, $memberId);
$stmt->execute();
$stmt->close();
}
?>
它有效,但它安全吗?
解决方案
它与通过 Internet 传输数据的任何其他方法一样安全,但您的方法似乎有点奇怪。
正如评论所指出的,处理此问题的常用方法是包含一个隐藏字段来传递应该对用户隐藏的数据。您仍然需要验证数据,因为用户也可以编辑隐藏的输入;他们只是从普通用户那里稍微混淆了它。
<form type="post" ...>
<input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
<input type="number" name="quantity" min="1" placeholder="Quantity" required >
...
</form>
<?php
$productId = $_POST['product_id'];
$quantity = $_POST['quantity'];
$query = 'UPDATE product SET quantity = ? WHERE product = ?'
...
编辑
如果您需要传递表单中的产品数据数组,您可以使用数组语法[]
来命名您的表单输入。
<?php
// This array just represents the data coming from your DB.
// Change it to suit.
$products = [
[
'id' => 1281,
'quantity' => 7
],
[
'id' => 234,
'quantity' => 2
],
[
'id' => 3455,
'quantity' => 25
],
[
'id' => 64563,
'quantity' => 84
],
[
'id' => 235,
'quantity' => 7
],
];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
var_dump($_POST);
// Handle the form processing here.
}
?>
<form method="post">
<?php foreach ($products as $product): ?>
<input type="hidden" name="product[<?php echo $product['id']; ?>]" value="<?php echo $product['id']; ?>">
<label for="product[<?php echo $product['id']; ?>]"><?php echo $product['id']; ?>:</label>
<input type="number" name="product[<?php echo $product['id']; ?>]" value="<?php echo $product['quantity']; ?>">
<br>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit">
</form>
输出:
array (size=2)
'product' =>
array (size=5)
1281 => string '52' (length=2)
234 => string '2' (length=1)
3455 => string '25' (length=2)
64563 => string '84' (length=2)
235 => string '7' (length=1)
'submit' => string 'Submit' (length=6)
然后,您可以遍历这些数据以创建 SQL 查询。
推荐阅读
- python - 如何从一组值中删除相似的组合
- php - 帮助理解比较 PHP 中两个 Unix 时间戳之间的差异
- reactjs - 奇怪:Eslint 为使用的变量提高 no-unused-vars
- mysql - 如何在 sql 的 Left Join 中仅显示表的左侧部分(不相交部分)?
- reactjs - 如何分叉为自定义构建创建 React 应用程序
- javascript - 解析元素标题中的 html 元素
- c++ - 如何使用 C++ 中的非文字变量在数字中显示单引号和两个引号?假设 6'2" 英尺
- wordpress - 如何删除添加到 Woo-commerce 中产品标题的短语
- ionic-framework - 如何执行此异步功能?
- javascript - 单击提交按钮后不出现确认框(Bootbox)