gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:26:36 27 4
gpt4 key购买 nike

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

有没有办法以“更漂亮的方式”编写它?你能看到其中有任何流动吗?我将不胜感激每一个帮助。

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

最佳答案

是的,有...

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

类似这样的事情:

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

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

关于php - PDO PHP bindParam() 重复使用相同的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48174978/

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