0

How would I go about populating a database from info in a csv file using PHP code? I need to practice using php to make database calls but at the moment, all I have access to is this csv file...

1

3 Answers 3

1

Design Considerations: You probably don't want to load the entire file into memory at once using a function like file_get_contents. With large files this will eat up all of your available memory and cause problems. Instead do like Adam suggested, and read one line at a time.

fgetcsv at php manual

//Here's how you would start your database connection
mysql_connect($serverName, $username, $password);
mysql_select_db('yourDBName');

//open the file as read-only
$file = fopen("file.csv", "r");

// lineLength is unlimited when set to 0
// comma delimited
while($data = fgetcsv($file, $lineLength = 0, $delimiter = ",")) {
   //You should sanitize your inputs first, using a function like addslashes
   $success = mysql_query("INSERT INTO fileTable VALUES(".$data[0].",".$data[1].")");
   if(!$success) {
     throw new Exception('failed to insert!');
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0

just do it through phpmyadmin: http://vegdave.wordpress.com/2007/05/19/import-a-csv-file-to-mysql-via-phpmyadmin/

Comments

0

Use the built-in PHP functions to read the CSV and write an output file. Then you can import the SQL into your database. This should work with any type of database.

Don't forget to escape any strings you are using. I used sqlite_escape_string() for that purpose in this example.

$fd = fopen("mydata.csv", "r");
$fdout = fopen("importscript.sql","w");

while(!feof($fd))
{
    $line = fgetcsv($fd, 1024); // Read a line of CSV

    fwrite($fdout,'INSERT INTO mytable (id,name)'
                 .'VALUES ('.intval($line[0]).",'".sqlite_escape_string($line[1])."');\r\n";
}

fclose($fdout);
fclose($fd);

3 Comments

Can you explain a little more what the sqlite function does? I did a searh on it and I'm still not exactly sure... And what is on your line[0] and on your line[1]?
sqlite_escape_string sanitizes your string so it won't break your query if it contains quotes.
$line[0] and $line[1] extract the first and second cell from the CSV row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.