tags:

views:

90

answers:

1

I'm inserting data from a file that has 18 columns, the table that I would like to insert it into has 20 columns. 2 of those columns already contain data. How do I go about inserting the file into the table without overwriting the existing data.

below is a example of the code. note $line .= ',,' is appending two columns because the update wont' work unless the columns match the exact table size of 20 columns. But the $line .= ',,' overwrites the data already inserted. What do i do?

$fcontents = file('data.txt'); 

if(mysql_error())
    echo mysql_error();

for($i=0; $i<sizeof($fcontents); $i++) 
{   
    //strip out double quotes
    $line = ereg_replace('"','',trim($fcontents[$i])); 

    $line .= ',,';

    //strip replace semi-colon with blank spaces
    $line = ereg_replace(';',' ',$line); 

    //single quote in parts records breaks replace code, removing single quote...
    $line = ereg_replace("'",'',$line); 


    //breaks apart the tab delimited row into a array
    $arr = explode(",", $line); 

    //add comma deliminted data back
    mysql_query("REPLACE INTO products VALUES ('". implode("','", $arr) ."')");


}
+4  A: 

Specify the column names:

REPLACE INTO products (col1, col2, ...) VALUES (val1, val2, ...)

See the MySQL online manual.

Andomar
how do i specify the column names in the implode?
payling
They go between "products" and "VALUES", no need to modify the implode!
Andomar
after entering the column names and removing the line.=',,' i still have problems replacing the values. Are you sure i don't have to do anything with the implode?mysql_query("REPLACE INTO products (col1, col2, col3) VALUES ('". implode("','", $arr) ."')"); is what i changed it do
payling
You did change "col1, col2, col3" to be the 18 column names you're trying to insert, right?
Andomar
the above code still deletes the two columns that are not specified in the replace... im confused, why would it do that?
payling
yep, the 18 columns replace fine... it's just it deletes the two extra columns of data that is not specified in the replace.
payling
Hrrm, I think replace deletes the row before inserting the data.. Probably need to use the update, but how do I use update with implode when I have to do set col1 = value1
payling
It's easiest to just write out the 18 columns I guess :) "UPDATE products SET col1 = $arr[0], col2 = ..."
Andomar
yep, thatis what i ended up doing.
payling