'this code is for insert only, my problem is how to prevent duplicate records before inserting [duplicate]
I want to show data input is already exist array
<?php
if(isset($_POST["med_nom"]))
{
$connect = new PDO("mysql:host=localhost;dbname=dbs", "", "password");
for($count = 0; $count < count($_POST["med_nom"]); $count++)
{
$query = "INSERT INTO medicinetbl (med_dorder, med_id, med_nom, med_qty, med_prc) VALUES (:med_dorder, :med_id, :med_nom, :med_qty, :med_prc)";
$statement = $connect->prepare($query);
$statement->execute(
array(
':med_dorder' => $_POST["med_dorder"][$count],
':med_id' => $_POST["med_id"][$count],
':med_nom' => $_POST["med_nom"][$count],
':med_qty' => $_POST["med_qty"][$count],
':med_prc' => $_POST["med_prc"][$count]
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
?>
Solution 1:[1]
This is how I check for duplicate Row ID's in my table:
# Generate random Row ID
$rid = rand(1000, 9999);
# start query (yours will be different as I have a class created for starting
# connections with PDO; nonetheless, you should still understand what im doing here)
$query_ridcheck = $db->connect->prepare("SELECT * FROM `table` WHERE rid=:rid");
$query_ridcheck->bindValue(':rid', $rid, PDO::PARAM_STR);
$query_ridcheck->execute();
# if it fetches any data back (while searching for the newly created $rid),
# then generate another random $rid again and check again. This while loop will
# keep going until it DOESN"T fetch any data back (meaning the random $rid has
# not been taken already).
while($query_ridcheck->fetch(PDO::FETCH_ASSOC)){
$rid = rand(1000, 9999);
$query_ridcheck = $db->connect->prepare("SELECT * FROM `table` WHERE rid=:rid");
$query_ridcheck->bindValue(':rid', $rid, PDO::PARAM_STR);
$query_ridcheck->execute();
}
Essentially, you can check for duplicate data before inserting, and choose what todo. I choose to regenerate the data and check again until I got a string/integer that wasn't a duplicate.
After this check, I go onto insert the data into the table using that row ID (since I now know it will not be taken)
Or like @Your_Common_Sense graciously pointed out, instead of repeating code you can also perform the same function like this:
# executes at lease once, then checks if the condition
# is true; If it is, continue looping until it's false.
do{
$rid = rand(1000, 9999);
$query_ridcheck = $db->connect->prepare("SELECT * FROM `table` WHERE rid=:rid");
$query_ridcheck->bindValue(':rid', $rid, PDO::PARAM_STR);
$query_ridcheck->execute();
}while($query_ridcheck->fetch(PDO::FETCH_ASSOC));
Solution 2:[2]
You should search into your data for the values you dont want to be repeated, if there is a record with the values, do not insert.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Isaac Batista |
