昨天我决定学习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();
有没有办法以“更漂亮的方式”写出来? 你能看到任何流动吗?我很感激你的每一个帮助。
注意:此代码将在不久的将来用于生产。
答案 0 :(得分:1)
是的,有......
您可以将bindParam
作为数组提供给execute
函数...
这样的事情:
$statement->execute([
':username'=> $username,
':password'=> $password
]);
它只在一个声明中使用bindParam
和execute
,在我看来它看起来更干净。
答案 1 :(得分:0)
是的,您可以通过定义mySql用户变量来解决重复的变量:
$ psVars = $ dbh-> prepare(“ SET @pid =:productID;”);
$ psVars-> bindParam(':productID',$ productID);
$ psVars-> execute();
然后,在后续语句中,仅使用@pid而不是绑定参数