Jump to content

[SOLVED] Populating a MySQL database from an excel file


mgs019

Recommended Posts

Hi,

 

I have an excel document with around 1000 records which I want to insert in to an SQL database. Is there an easy way to do this? I know I must get the data in a regularised format and so on first but is there an easy set of php commands to take a file apart and turn it to sql. I thought maybe from a tab delimited file? I want to be able to update regularly as I get an updated spreadsheet every week so I wanted to make a page to delete all the records and then repopulate with the new version. What I do not want to do is enter 1000 records manually!!!

 

Any help will be appreciated,

 

Martin

Link to comment
Share on other sites

I have a few clients that would like to easily import new data into their database...They download the current products in excel, make price changes, then upload the same excel file in the same format. Here is what I use:

 

<?php
// mysql connection script ... 

// tab delimited file 
$file = "All_Catalog_Manufacturers.xls"; 

// open file 
$handle = fopen($file, "r"); 

$x = 0;
echo "<table border=1>";
// loop through results with fgetcsv() function 
while(($data = fgetcsv($handle, 1000, "\t")) !== FALSE) { 
     
    // populate field vars just to make it easier to work with ..  
    // you could access the $data[] array directly in the sql if you want 
    $field1 = $data[0]; 
    $field2 = $data[1]; 
    $field3 = $data[2]; 
    $field4 = $data[2]; 
    // etc ... 
     
    // build your sql statement 
    $sql = "insert into table set  
                                testid='1', 
                                category='foo', 
                                field1='".$field1."', 
                                field2='".$field2."', 
                                field3='".$field3."'"; 
     
    //if($x >0) $result = mysql_query($sql); 

if($x >0) echo "<tr><td>$field1</td><td>$field2</td><td>$field3</td></tr>";

$x++;
} 
echo "</table>";
// close file 
fclose($handle); 


?> 

 

***I just have that outputting to a table, but you can just comment out the echo to the table and un-comment the mysql query.

 

hope this helps

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.