Jump to content

avoiding duplicate entry in mysql database


adi1991

Recommended Posts

I have craated one web form to upload csv sheet to mysql database, the primary key is "sample name" in database, i am trying to avoid duplication of "samplename" before uploading to database. my question is , Is it possible to do so?

<html>
    <body>
        <form action="dform.php" method="post" enctype="multipart/form-data">
             
            <input name="csv" type="file" id="csv" accept=".xls"/> <br /> <br />
 
            <input type="submit" name="Submit" value="UPDATE" /> 
        </form>
    </body>
</html>

above i saved as "dform.html"

<?php 
if (!$_POST) 
{ 
?>

<?php
} else {
$connect = new mysqli("localhost", "root", "", "ProcessTrackingSystem");
if ($_FILES[csv][size] > 0) {
    //get the csv file 
    $file = $_FILES[csv][tmp_name]; 
    $handle = fopen($file, "r");
    $i = 0;
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if ($i > 0) {
$import = ("INSERT INTO ProcessTrackingSystem.ProcessDetails VALUES('" . implode("','", $data) . "');");
            $connect->query($import);
        }
        $i++;
    }
    fclose($handle);
    echo "THANKS FOR UPLOADING"."<br>"."<br>";	
	echo "Hit Back Button to UPLOAD MORE Data Sheets";
}
}
?>

above code i saved as "dform.php".

 

any doughts and clarifications regarding above asked question are welcome.

Yes, you can set the samplename field to be unique

ALTER TABLE ProcessDetails ADD UNIQUE(samplename)

Now when you go to insert a duplicate value into the samplename field an error will be triggered and the insert query will fail, if you do want to the error to be triggered then change your INSERT query to INSERT IGNORE or if you want the insert query to update the existing data for that row, then use INSERT ON DUPLICATE KEY UPDATE query

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.