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

Scott Yong Asked:
Who is Participating?
 
Chris StanyonConnect With a Mentor Commented:
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
 
Chris StanyonCommented:
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
Improve Your Query Performance Tuning

In this FREE six-day email course, you'll learn from Janis Griffin, Database Performance Evangelist. She'll teach 12 steps that you can use to optimize your queries as much as possible and see measurable results in your work. Get started today!

 
Chris StanyonCommented:
@Julian

File name as the detection for duplicated files
0
 
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 StanyonCommented:
Hey Julian,

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

Previous comment was aimed more at the 'binary level' comparison
0
 
Scott Yong 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 StanyonCommented:
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
 
Scott Yong 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
 
Scott Yong Author Commented:
If i checking only the error during the upload session , if file exist so echo error ~
0
 
Scott Yong 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 StanyonCommented:
What error are you getting ?
0
 
Scott Yong Author Commented:
Its work already ~I tried to edit some code and its work
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.