pdo php bindparam()重复使用相同的参数

zujrkrfu  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(394)

昨天我决定学习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();

有没有办法用“更漂亮的方式”来写呢?你能看到里面有什么流动吗。我会非常感激你的帮助。
注:此代码将在不久的将来用于生产。

vjhs03f7

vjhs03f71#

是的,您可以通过如下方式定义mysql用户变量来绕过重复的变量:
$psvars=$dbh->prepare(“set@pid=:productid;”);
$psvars->bindparam(':productid',$productid);
$psvars->execute();
然后,在随后的语句中,只需使用@pid而不是绑定参数

uurv41yg

uurv41yg2#

是的,有。。。
你可以提供 bindParam 作为一个数组 execute 函数。。。
像这样:

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

它正在使用 bindParam 以及 execute 在我看来,它看起来更干净。

相关问题