gpt4 book ai didi

php - 如何正确绑定(bind) PHP 准备和执行语句?

转载 作者:太空宇宙 更新时间:2023-11-03 12:14:36 25 4
gpt4 key购买 nike

我有一个函数可以在数据库中插入或更新一个值。

我正在使用准备和执行语句,我想匹配我的函数的 ELSE 子句以匹配准备好的语句。

在我的 ELSE 子句中,我还有一个值(即 $id),所以我不确定是否可以在执行数组中分配它。

function insert_value($item_name, $description, $supplier_code, $cost, $sell_price,$num_on_hand, $reorder_point, $back_order, $id=0)
{

$connection = db_connect();
if($id==0)
{
$sql = 'INSERT INTO inventory (itemName, description, supplierCode, cost, price, onHand, reorderPoint, backOrder)
VALUES(:itemName, :description, :supplierCode, :cost, :price, :onHand, :reorderPoint, :backOrder);';
}
else
{
//NEED TO CHANGE THIS PART
$sql = "UPDATE inventory SET itemName='$item_name', description='$description', supplierCode='$supplier_code',
cost='$cost', price='$sell_price', onHand='$num_on_hand', reorderPoint='$reorder_point', backOrder='$back_order'
WHERE id='$id'";
}

$prepare = $connection->prepare($sql);
$prepare->execute(array( // AND THIS PART
":itemName" => $item_name,
":description" => $description,
":supplierCode" => $supplier_code,
":cost" => $cost,
":price" => $sell_price,
":onHand" => $num_on_hand,
":reorderPoint" => $reorder_point,
":backOrder" => $back_order,
));
}

最佳答案

类似于:

function insert_value($item_name, $description, $supplier_code, $cost, $sell_price,$num_on_hand, $reorder_point, $back_order, $id=0){
$connection = db_connect();
$arr = array(":itemName" => $item_name,
":description" => $description,
":supplierCode" => $supplier_code,
":cost" => $cost,
":price" => $sell_price,
":onHand" => $num_on_hand,
":reorderPoint" => $reorder_point,
":backOrder" => $back_order);
if($id==0){
$sql = 'INSERT INTO inventory (itemName, description, supplierCode, cost, price, onHand, reorderPoint, backOrder)
VALUES(:itemName, :description, :supplierCode, :cost, :price, :onHand, :reorderPoint, :backOrder)';
}else{
$sql = "UPDATE inventory SET itemName=:itemName, description=:description, supplierCode=:supplierCode,
cost=:cost, price=:price, onHand=:onHand, reorderPoint=:reorderPoint, backOrder=:backOrder
WHERE id=:id";
$arr[":id"] = $id;
}

$prepare = $connection->prepare($sql);
$prepare->execute($arr);
}

此外,您可能还想检查(如果您还没有这样做)以查看 $connection 是否有效,否则在准备/执行时您可能会遇到错误。

关于php - 如何正确绑定(bind) PHP 准备和执行语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22755906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com