【发布时间】:2018-01-09 18:58:06
【问题描述】:
昨天我决定学习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();
有没有办法以“更漂亮的方式”编写它? 你能看到里面的任何流动吗?我将不胜感激。
注意:此代码将在不久的将来用于生产。
【问题讨论】:
-
顺便说一句,您忘记在 DELETE 语句中使用参数。上次更新时相同。
-
好一个。谢谢我的朋友!
-
如果你想设置新值而不是现有值,你应该使用
ON DUPLICATE KEY UPDATE customerID = VALUES(customerID)。 -
我不想设置新的而不是现有的。这是我从stackoverflow上的一个人那里看到的一个技巧。它说插入,但是,如果已经存在,则不快速执行任何操作。
-
为什么不直接使用
INSERT IGNORE呢?使用INSERT...ON DUPLICATE KEY UPDATE执行插入,然后可能执行更新。