PDO PHP bindParam() 重复使用相同的参数

PDO PHP bindParam() repeated use of same parameters

昨天我决定学习 PDO 并将我们的服务器 php 重写为 PDO。

我在重写代码时突然想到的是需要对我已经使用过的相同参数重复使用 bindParam。

这是一个例子:

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $dbh->beginTransaction();
    $stmt = $dbh->prepare("INSERT INTO Products(productID,numOfLikes) VALUES (:productID,0) ON DUPLICATE KEY UPDATE productID = productID;");
    $stmt->bindParam(":productID",$productID);
    $stmt->execute();

    if($customerID !== 0){  
        //*****Check, if customerID is in the Database, else add the customerID to the Database.
        $stmt = $dbh->prepare("INSERT INTO Customers(customerID) VALUES (:customerID) ON DUPLICATE KEY UPDATE customerID = customerID;");
        $stmt->bindParam(":customerID",$customerID);
        $stmt->execute();

        //*****if customerID and productID are NOT registered together ,then register and add +1 to productID numOfLikes
        $stmt = $dbh->prepare("SELECT customerID, productID FROM CustomerProducts WHERE productID = :productID AND customerID = :customerID");          
        $stmt->bindParam(":productID",$productID);
        $stmt->bindParam(":customerID",$customerID);
        $stmt->execute();

        if ($stmt->rowCount() == 0) {
            //echo "added";
            $stmt = $dbh->prepare("INSERT INTO CustomerProducts(customerID, productID) Values (:customerID,:productID)");
            $stmt->bindParam(":customerID",$customerID);
            $stmt->bindParam(":productID",$productID);
            $stmt->execute();

            $stmt = $dbh->prepare("UPDATE Products SET numOfLikes = numOfLikes + 1 WHERE productID = :productID");
            $stmt->bindParam(":productID",$productID);
            $stmt->execute();  
        }else {
            //echo "removed";
            $stmt = $dbh->prepare("DELETE FROM CustomerProducts WHERE productID = ".$productID." AND customerID = ".$customerID);
            $stmt->bindParam(":customerID",$customerID);
            $stmt->bindParam(":productID",$productID);
            $stmt->execute();

            $stmt = $dbh->prepare("UPDATE Products SET numOfLikes = numOfLikes - 1 WHERE productID = ".$productID);
            $stmt->bindParam(":productID",$productID);
            $stmt->execute();  
        }
    }
    $dbh->commit();

有没有办法写成"prettier way"? 你能看到其中的任何流量吗?我将不胜感激。

注意:此代码将在不久的将来用于生产。

是的,有...

您可以将 bindParam 作为数组提供给 execute 函数...

像这样:

$statement->execute([
    ':username'=> $username,
    ':password'=> $password
]);

它在一个语句中使用了 bindParamexecute,在我看来它看起来更干净。

是的,您可以像这样定义 mySql 个用户变量来绕过重复变量:

$psVars = $dbh->准备("SET @pid = :productID;");

$psVars->bindParam(':productID', $productID);

$psVars->执行();

然后,在后续语句中,只需使用@pid 代替绑定参数