Home > database >  this code is for insert only, my problem is how to prevent duplicate records before inserting
this code is for insert only, my problem is how to prevent duplicate records before inserting

Time:05-19

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';
 }
}
?>

CodePudding user response:

You can define your bank keys and use
INSERT IGNORE (which will ignore if there is any record with the same key).
REPLACE INTO (which will replace if it finds a record with the same key).

Or you can do an initial search in your base and based on that result, update or insert

$query = "INSERT IGNORE INTO medicinetbl";
$query = "REPLACE INTO medicinetbl";

Documentation MySQL INSERT Documentation MySQL REPLACE

CodePudding user response:

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)

CodePudding user response:

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.

  • Related