function loopFunction(PDO $pdo, $products) {
$pdo->beginTransaction();
foreach($products as $uid => $element) {
$isPremium = $element[0] != false && in_array('isPremium', $element[0]) ? 1 : 0;
$isExclusive = $element[0] != false && in_array('isExclusive', $element[0]) ? 1 : 0;
$isLimited = $element[0] != false && in_array('isLimited', $element[0]) ? 1 : 0;
$IsNew = $element[0] != false && in_array('IsNew', $element[0]) ? 1 : 0;
$DirectCallId = isset($element[1]) ? $element[1] : false;
insertOrUpdate($pdo, $isPremium, $isExclusive, $isLimited, $IsNew, $DirectCallId, $uid);
}
$pdo->commit();
}
function insertOrUpdate(PDO $pdo, $isPremium, $isExclusive, $isLimited, $IsNew, $DirectCallId, $uid) {
$sql = "SELECT COUNT(*) AS numberRows FROM [PaynowCom].[DirectCall].[Report] WHERE ReportId = (:value1)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':value1', $DirectCallId);
$stmt->execute();
$count = (int)$stmt->fetchColumn();
if ($count) {
$sql2 = "UPDATE TOP(1) [PaynowCom].[DirectCall].[Report]
SET isPremium = (:value1), isExclusive= (:value2), isLimited = (:value3), IsNew = (:value4)
WHERE reportId = (:value5)";
$stmt2 = $pdo->prepare($sql2);
$stmt2->bindParam(':value1', $isPremium);
$stmt2->bindParam(':value2', $isExclusive);
$stmt2->bindParam(':value3', $isLimited);
$stmt2->bindParam(':value4', $IsNew);
$stmt2->bindParam(':value5', $DirectCallId);
if (!$stmt2->execute()) {
print_r('error');
}
} else {
$sql2 = "INSERT INTO [PaynowCom].[DirectCall].[Report]
(created, reportId, uid, isPremium, isExclusive, isLimited, IsNew)
VALUES (getdate(), :value1, :value2, :value3, :value4, :value5, :value6)";
$stmt2 = $pdo->prepare($sql2);
$stmt2->bindParam(':value1', $DirectCallId);
$stmt2->bindParam(':value2', $uid);
$stmt2->bindParam(':value3', $isPremium);
$stmt2->bindParam(':value4', $isExclusive);
$stmt2->bindParam(':value5', $isLimited);
$stmt2->bindParam(':value6', $IsNew);
if (!$stmt2->execute()) {
print_r('error');
}
}
I think this can be improved a lot, but I am more concerned about how the transaction would work, because I am doing a conditional insert inside the code and I am wondering if the transaction would work as expected since we have multiple MSSQL prepared statements and not just 1 for each element.
I think the insert or update could be improved and we could use something else, but I am more preoccupied with the transaction and how it works with pdo.
I heard that conditional insert can cause duplicate keys or deadlocks, but I am not too sure about that.