We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

PHP - CSV file import routine

BenthamLtd
BenthamLtd asked
on
Medium Priority
583 Views
Last Modified: 2012-05-11
Dear all,

Wrote an import routine, can't get it to work. Mind taking a quick look at the code and feeding back any ideas? Thanks.
<?php require_once('_config.php'); ?>

<?php
## import existing database ##
// 

    if(isset($_POST['submit']))
    {
         $fname = $_FILES['sel_file']['name'];
        
         $chk_ext = explode(".",$fname);
		 
		 var_dump($chk_ext);
        
         if(strtolower($chk_ext[1]) == "csv")
         {
        
             $filename = $_FILES['sel_file']['tmp_name'];
             $handle = fopen($filename, "r");
       
             while ($data = fgetcsv($handle, 1000, ",") != FALSE)
             {
                $import_query = "INSERT INTO clients (membershipNo, firstname, lastname, dob, email, telephone, contactable, shopID, issueruserID, idproof, type) VALUES ('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]') ";
                mysql_query($import_query) or die(mysql_error());
             }
       
             fclose($handle);
             echo "Successfully Imported";
         }
         else
         {
             echo "Invalid File";
         }   
    }

?>

    <form action='<?php echo $_SERVER["PHP_SELF"]; ?>' method='post'>

        Import File : <input type='text' name='sel_file' size='99'>
        <input type='submit' name='submit' value='submit'>

    </form>
<body>
</body>
</html>

Open in new window

Comment
Watch Question

Top Expert 2007
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Commented:
is your file separated by a fullstop?
if not change:

$chk_ext = explode(".",$fname);

(just a stab in the dark ....)
Most Valuable Expert 2011
Author of the Year 2014

Commented:
Line 9 says this:  $fname = $_FILES['sel_file']['name'];

But see the form on line 38.  There is no enctype attribute nor any input type=file statement.

If you want to upload a file this is a good place to start the learning process:
// MANUAL REFERENCE PAGES
// http://docs.php.net/manual/en/features.file-upload.php
// http://docs.php.net/manual/en/features.file-upload.common-pitfalls.php
// http://docs.php.net/manual/en/function.move-uploaded-file.php

Most Valuable Expert 2011
Author of the Year 2014
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Ok thanks for the ideas so far everyone. The .csv file I'm trying to upload is in the root of the site where the upload.php is running. The CSV file is called 'camborne.csv'.

We can probably strip out all the error checking in this script to make it easier if needs be. It's a one-time shot for uploading a group of CSV files. When they are on the database, we can disregard this script!

Many thanks guys, really appreciate the excellent advice on here.

Author

Commented:
Ok as an update to this, I've commented out all the rubbish error checking. It seems to work but is only inserting blank rows. Any ideas? Code attached (also tried experimenting with sprintf)


<?php
## import existing database ##
// 

  #  if(isset($_POST['submit']))
  #  {
  #       $fname = $_FILES['sel_file']['name'];
        
  #       $chk_ext = explode(".",$fname);
		 
#		 var_dump($chk_ext);
        
 #        if(strtolower($chk_ext[0]) == "csv")
 #        {
        
  #           $filename = $_FILES['sel_file']['tmp_name'];
  			$filename = $_FILES['sel_file']['name'];
      
	     #    $handle = fopen($filename, "r");
       $handle = fopen('camborne.csv', "r");
             while (($data = fgetcsv($handle, 1000, ",") !== FALSE))
             {
                $import_query = sprintf("INSERT INTO clients (membershipNo, firstname, lastname, dob, email, telephone, contactable, shopID, issueruserID, idproof, type) VALUES ('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]') ");
                mysql_query($import_query) or die(mysql_error());
             }
       
             fclose($handle);
             echo "Successfully Imported";
   #      }
     #    else
    #     {
      #       echo "Invalid File";
      #   }   
  #  }

?>

    <form action='<?php echo $_SERVER["PHP_SELF"]; ?>' method='post'>

        Import File : <input type="file" name='sel_file' size='99'>
        <input type='submit' name='submit' value='submit'>

    </form>

Open in new window

Author

Commented:
OK just got it to work, basically stripped out all error checking. Posting code, thanks for the help guys.

Think I will whack a mysql_real_escape_string in there just in case though (as it will indeed, f--k up the query).


I'll split points for the info that worked.

Author

Commented:

<?php

$filename = $_FILES['sel_file']['name'];
      
$handle = fopen('test.csv', "r");

while ($data = fgetcsv($handle, 1000, ","))
   {
     $import_query = "INSERT INTO clients (membershipNo, firstname, lastname, dob, email, telephone, contactable, shopID, issueruserID, idproof, type) VALUES ('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]') ";
     mysql_query($import_query) or die(mysql_error());
				
     echo $import_query;   // just to see if it worked, not many lines per CSV luckily so shouldnt kill the browser
   }
       
fclose($handle);
echo "Successfully Imported";

?>

Open in new window

Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.