Jump to content

[SOLVED] Reading / Inserting a CSV File


JSHINER

Recommended Posts

I have a CSV file that looks like this:

 

Apple,Orange,Banana,Pear

 

I am trying to use this code to insert it into a database:

 

<?php

require('Database.php');
$db = new Database();

$handle = fopen('file.csv', 'r');

while ($row = fgetcsv($handle)) {
$that = $db->escape(trim($row[0]));
$db->query("INSERT INTO table SET this = '$that'");
}
fclose($handle);
$db->close();

?>

 

But it only inserts the first record. What is wrong?

Link to comment
https://forums.phpfreaks.com/topic/123372-solved-reading-inserting-a-csv-file/
Share on other sites

I use this code: Works fine!!

 

 

<?php

include("mainpage.php");

include("database.php");

 

if(count($_FILES))

{

 

$dir = 'files/';

if(is_uploaded_file($_FILES['inputfile']['tmp_name'])) {

move_uploaded_file($_FILES['inputfile']['tmp_name'], $dir.$_FILES['inputfile']['name']);

$inputfile = $_FILES['inputfile']['name'];

}

 

$file = fopen($dir.$inputfile, "r") or exit("Unable to open file!");

 

fgets($file);

executeNonQuery("delete from inventory where fund='HI'");

$countline = 0;

 

while(!feof($file))

{

$line = fgets($file);

$linedata = explode(',', $line);

 

if(count($linedata) == 7)

{

 

if(strlen(trim($linedata[0])))

{

$query =  "insert into inventory(tool_id, Process, Description, Manufacturer, Model, Wafer_max, in_production,serial_number,description, fund) values (";

$query .= "'$linedata[0]', '$linedata[1]', '$linedata[2]', '$linedata[3]', '$linedata[4]', '$linedata[5]', '$linedata[6]','$linedata[7]','$linedata[8]','Hi')";

executeNonQuery($query);

}

$countline++;

}

}

fclose($file);

echo '<h3>Data extracted successfully! Total '.$countline.'<h3/>';

}

else

{

?>

 

<form action="<?$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">

<input type="file" name="inputfile" />

<input type="submit" value="Extract"/>

</form>

<?php

}

include("footer.php");

?>

 

Dont forget to store ur csv in new folder "files".

 

Hope this works!!

Another way is to use an outside file reader class.

 

I used Spreadsheet Factory and it is FANTASTIC for reading some of the most common Excel formats.

 

Here is a link for you:  http://code.google.com/p/php-spreadsheetreader/

 

It is really very simple code to work with in my opinion.

 

Best of luck mate.

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.