This is the console data POST, I am trying to create a function where if array value does not exist in the database then it will insert, and If the database value not matched with the array value then the value which already existed in the database will be deleted.
I created the code, it deletes the already inserted value and regains inserts the value in the array.
I also read the other threads similar the post but all was not helpful.
Please help me, How I achieve the function.
Insert array value if not exist in DB
Delete the value if the Database Column Value not matched with the array value.
console sent post data -
state: 14506
district: 16564
pincode[]: 844101
pincode[]: 844102
pincode[]: 844103
pincode[]: 844111
PHP ARRAY
Array
(
[state] => 14506
[district] => 16564
[pincode] => Array
(
[0] => 123
[1] => 456
[2] => 789
)
)
PHP SQL
$sqlInsert = "INSERT INTO `table` (`alt_pincode`,`alt_district`,`alt_state`)VALUES (:pin,:district,:state)";
$stmtInsert = $con->prepare($sqlInsert);
foreach ($_POST['pincode'] as $key => $binded_pinvalue) {
if (!empty($binded_pinvalue)) {
$stmt = $con->prepare("SELECT * FROM `table` WHERE `state` = :state AND `district` = :district AND `pin` = :pincode");
$stmt->execute([
':district' => $district,
':state' => $state,
':pin' => $binded_pinvalue,
]);
if ($stmt->rowCount() > 0) {
$stmt = $con->prepare("DELETE FROM `table` WHERE `state` = :state AND `district` = :district AND `pin` = :pincode");
$stmt->execute([
':district' => $district,
':state' => $state,
':pin' => $binded_pinvalue,
]);
} else {
//INSERT FUNCTION
$stmtInsert->bindParam(':pin', $binded_pinvalue, PDO::PARAM_STR);
$stmtInsert->bindParam(':district', $district, PDO::PARAM_STR);
$stmtInsert->bindParam(':state', $state, PDO::PARAM_STR);
$stmtInsert->execute();
}
}
}
also used this code but repeating - Inserts
foreach ($_POST['pincode'] as $key => $binded_pinvalue) {
$stmt = $con->prepare("DELETE FROM `table` WHERE `state` = :state AND `district` = :district AND `pin` = :pincode");
$stmt->execute([
':district' => $district,
':state' => $state,
':pin' => $binded_pinvalue,
]);
}
foreach ($_POST['pincode'] as $key => $binded_pinvalue) {
//INSERT FUNCTION
$stmtInsert->bindParam(':pin', $binded_pinvalue, PDO::PARAM_STR);
$stmtInsert->bindParam(':district', $district, PDO::PARAM_STR);
$stmtInsert->bindParam(':state', $state, PDO::PARAM_STR);
$stmtInsert->execute();
}
Please help me, it inserting again and again and deletes exists value. How I make it correct