How to alert duplicate files when upload csv files

I want to alert a message " Sorry file already existed " when user upload the same files , if the files didn't exist in the database , user can upload the files into database . File name as the detection for duplicated files .

<?php
include 'config.php';


if(isset($_POST['btn-upload']))
{  


$targetDir = "uploads/";
$files = $_FILES['file'];
foreach($files['name'] as $key => $name) {
    $file = $files['tmp_name'][$key];
    $target = $targetDir  . "/" . $name; 
	    

		
		
    if (is_uploaded_file($file)) {
		
		 //open uploaded csv file with read only mode
            $csvFile = fopen($file, 'r');
            
            //skip first line
            fgetcsv($csvFile);
            
            //parse data from csv file line by line
            while(($line = fgetcsv($csvFile)) !== FALSE){
                 //insert member data into database
                    $db->query("INSERT INTO nov(f_name,name, cpu_count, memory_size, disk_space_size, nic_count, power_state) VALUES ('".$name."','".$line[0]."','".$line[1]."','".$line[2]."','".$line[3]."','".$line[4]."','".$line[5]."')");
                }
            
            ?>
  <script>
  alert('successfully uploaded');
        window.location.href='index.php?success';
        </script>
  <?php
  }
 else
 {
  ?>
  <script>
  alert('error while uploading file');
        window.location.href='index.php?fail';
        </script>
  <?php
 }
}		
            //close opened csv file
            fclose($csvFile);
		
		
		
	}

?>

Open in new window

Yong Scott Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
The general idea here is that you set your filename column at the DB level to be a unqiue constraint. That way, the DB will automatically throw an error when you try to insert a value that already exists. The error thrown will have the Error Number of 1022, so you can check that and act accordingly. The $db->query will return false if it fails, so you would need to wrap it all up in an if statement:

if ( !$db->query("INSERT INTO nov(f_name,name, cpu_count, memory_size, disk_space_size, nic_count, power_state) VALUES ('".$name."','".$line[0]."','".$line[1]."','".$line[2]."','".$line[3]."','".$line[4]."','".$line[5]."')") ):
    // we have an error
    if ($db->errno == '1022'):
        // we tried to insert a duplicate
    else:
        // we have a different error
    endif;
endif;

Open in new window

0
Julian HansenCommented:
What constitutes "the same file"?
File has the same name - if so does the case used in the filename count?
File is identical on the binary level when compared to some existing file?
0
Chris StanyonWebDevCommented:
@Julian

File name as the detection for duplicated files
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Julian HansenCommented:
@Chris,
So we just ignore case and if the user uploads File1.pdf and there is a file1.pdf on disk then we count those as separate files?
0
Chris StanyonWebDevCommented:
Hey Julian,

Don't know about case - have to wait and see :)

Previous comment was aimed more at the 'binary level' comparison
0
Yong Scott Author Commented:
What constitutes "the same file"?

Example like File1.csv , then the next upload File1.csv is invalid because already exist in database .

unqiue constraint.
I got no unique constraint because have to display the record for each file name .

Cap2ture.PNG
I think i will add one column name number list which is starting from 1 , maybe that number list as unique constraint
0
Chris StanyonWebDevCommented:
OK, so the filename is not going to be unique in the DB table. You will need to run a SELECT query on the DB to check if it already exists before inserting the records. Something like this:

$result = $db->query("SELECT Count(*) AS count FROM youtTable WHERE someField = yourFileName");

if ($result->fetch_object()->count > 0):
    echo "<p>The filename already exists in the DB</p>";
else:
    echo "<p>The filename doesn't exist in the DB</p>";
endif;

Open in new window

1
Yong Scott Author Commented:
Fatal error: Uncaught Error: Call to a member function fetch_object() on boolean in C:\xampp\htdocs\db_v3\upload.php:31 Stack trace: #0 {main} thrown in C:\xampp\htdocs\db_v3\upload.php on line 31

$result = $db->query("SELECT Count(*) AS count FROM nov WHERE f_name = $name");

if ($result->fetch_object()->count > 0):
    echo "<p>The filename already exists in the DB</p>";
else:
    echo "<p>The filename doesn't exist in the DB</p>";
endif;

Open in new window


I get the error
0
Chris StanyonWebDevCommented:
OK. The call to query() will return either a mysqli_result object if it's succesful, or FALSE if it fails. It looks like your query is failing, probably because you don't have any quotes around the $name variable, so it returns FALSE. Wrap you $name in single quotes:

$result = $db->query("SELECT Count(*) AS count FROM nov WHERE f_name = '$name'");

Open in new window

You can add some error handling for this by explicitly checking the $result before calling fetch_object():

if ($result = $db->query("SELECT Count(*) AS count FROM nov WHERE f_name = '$name'")):

    if ($result->fetch_object()->count > 0):
        echo "<p>The filename already exists in the DB</p>";
    else:
        echo "<p>The filename doesn't exist in the DB</p>";
    endif;

else:

    printf("The query failed: %s", $db->error);

endif;

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Yong Scott Author Commented:
If i checking only the error during the upload session , if file exist so echo error ~
0
Yong Scott Author Commented:
if ($result = $db->query("SELECT Count(*) AS count FROM nov WHERE f_name = '$name'")):

    if ($result->fetch_object()->count > 0):
        echo "<p>The filename already exists in the DB</p>";
    else:
        echo "<p>The filename doesn't exist in the DB</p>";
    endif;

else:

    printf("The query failed: %s", $db->error);

endif;

Open in new window


There is some syntax error
0
Chris StanyonWebDevCommented:
What error are you getting ?
0
Yong Scott Author Commented:
Its work already ~I tried to edit some code and its work
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Databases

From novice to tech pro — start learning today.