通过准备好的语句更新 sql 中的部分行
Update apart of row in sql by prepared statements
我得到了一个产品 table,其中包含 ID、名称、描述、颜色、价格、数量和状态
如何使用准备好的语句仅更新名称、描述或连续更新 2-3 个字段。例如,我的准备语句是
UPDATE product SET product_name = ?, product_desc = ?,product_size = ?, product_color = ?,product_price = ?,product_quantity = ?, product_status = ? WHERE id = $id
bind_param
看起来像这样
bind_param("ssssiii", $data['name'], $data['desc'], $data['size'], $data['color'], $data['price'], $data['quantity'], $data['status'])
并假定 $data['color']
和 $data['quantity']
为空,那么我如何更新数据库中的该行以保留 product_color
和 product_quantity
列的旧值.
它会在执行更新语句时自动保留旧数据,还是我必须对类似的东西进行一些验证?
这是我的代码:
$connect = new mysqli(HOST,USER,PASSWORD,DATABASE);;
$sql = "UPDATE product SET product_name = ?, product_desc = ?,product_size = ?,
product_color = ?,product_price = ?,product_quantity = ?, product_status = ?
WHERE id = $id";
$stmt = $connect->prepare($sql);
$stmt->bind_param("ssssiii", $data['name'], $data['desc'], $data['size'], $data['color'],
$data['price'],$data['quantity'],$data['status']);
$stmt->execute();
$stmt->close();
如果我没理解错的话,你可以用coalesce()
:
UPDATE $tableName
SET product_name = COALESCE(?, product_name),
product_desc = COALESCE(?, product_desc),
product_size = COALESCE(?, product_size),
product_color = COALESCE(?, product_color),
product_quantity = COALESCE(?, product_quantity),
product_status = COALESCE(?, product_status)
WHERE id = ?;
备注:
- 当您不想设置值时,这假设传入的参数是
NULL
。
- 您不能将列设置为
NULL
。
- 我更改了
WHERE
所以它引用了一个参数。
我得到了一个产品 table,其中包含 ID、名称、描述、颜色、价格、数量和状态
如何使用准备好的语句仅更新名称、描述或连续更新 2-3 个字段。例如,我的准备语句是
UPDATE product SET product_name = ?, product_desc = ?,product_size = ?, product_color = ?,product_price = ?,product_quantity = ?, product_status = ? WHERE id = $id
bind_param
看起来像这样
bind_param("ssssiii", $data['name'], $data['desc'], $data['size'], $data['color'], $data['price'], $data['quantity'], $data['status'])
并假定 $data['color']
和 $data['quantity']
为空,那么我如何更新数据库中的该行以保留 product_color
和 product_quantity
列的旧值.
它会在执行更新语句时自动保留旧数据,还是我必须对类似的东西进行一些验证?
这是我的代码:
$connect = new mysqli(HOST,USER,PASSWORD,DATABASE);;
$sql = "UPDATE product SET product_name = ?, product_desc = ?,product_size = ?,
product_color = ?,product_price = ?,product_quantity = ?, product_status = ?
WHERE id = $id";
$stmt = $connect->prepare($sql);
$stmt->bind_param("ssssiii", $data['name'], $data['desc'], $data['size'], $data['color'],
$data['price'],$data['quantity'],$data['status']);
$stmt->execute();
$stmt->close();
如果我没理解错的话,你可以用coalesce()
:
UPDATE $tableName
SET product_name = COALESCE(?, product_name),
product_desc = COALESCE(?, product_desc),
product_size = COALESCE(?, product_size),
product_color = COALESCE(?, product_color),
product_quantity = COALESCE(?, product_quantity),
product_status = COALESCE(?, product_status)
WHERE id = ?;
备注:
- 当您不想设置值时,这假设传入的参数是
NULL
。 - 您不能将列设置为
NULL
。 - 我更改了
WHERE
所以它引用了一个参数。