如何正确绑定PHP准备和执行语句?

时间:2014-03-31 07:34:52

标签: php mysql sql

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

我正在使用prepare和execute语句,我希望匹配我的函数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,
        ));
}

1 个答案:

答案 0 :(得分:3)

类似的东西:

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是否有效,否则一旦准备/执行,您可能会收到错误。