/    Sign up×
Community /Pin to ProfileBookmark

Parsing a CSV file with PHP

I am using the following code:

[code=php]
<?

//CONFIG VALUES TO SHOW WHICH COMPANY AND EMAIL LIST DATA IS ENTERED FOR
$list_id = “85”;
$company_id = “40”;

//CONNECTS TO THE MYSQL DATABASE WHERE DATA WILL BE STORED
$link = mysql_connect(“localhost”, “user”, “password”) or die(“Could not connect: “.mysql_error());
$db = mysql_select_db(“database”) or die(mysql_error());

//SETS ROW VALUE OF 1
$row = 1;

//OPENS CSV FILE
$handle = fopen (“good_csv.csv”,”r”);

//PARSES INFORMATION
while ($data = fgetcsv ($handle, 1000, “,”)) {

//ONLY SELECTS RECORDS WITH A FIRST NAME, LAST NAME, AND EMAIL
if($data[0] != “” && $data[1] != “” && $data[2] != “”) {

//FIRST QUERY INSERTS EMAIL AND LIST INTO SUBSCRIBERS TABLE
$query = “INSERT INTO subscribers(`list_id`,`email`) VALUES(‘”.$list_id.”‘, ‘”.$data[0].”‘)”;
$result = mysql_query($query) or die(“Invalid query: ” . mysql_error().__LINE__.__FILE__);

//GRABS ID FROM QUERY FOR LOYALTYMAX CUSTOMER TABLE
$subscriber_id = mysql_insert_id();

//SECOND QUERY BUILDS CUSTOMER PROFILE IN LOYALTY CUSTOMER DATABASE
$query2 = “INSERT INTO loyaltymax_customer(`first_name`,`email`,’company_id’,’last_name’,’list_id’,’subscriber_id’) VALUES(‘”.$data[0].”‘,'”.$data[1].”‘,'”.$company_id.”‘,'”.$data[1].”‘,'”.$list_id.”‘,'”.$subscriber_id.”‘)”;
$result2 = mysql_query($query2) or die(“Invalid query: ” . mysql_error().__LINE__.__FILE__);

//PRINTS EACH RECORD
echo(“{$row}. {$data[0]}, {$data[1]}, {$data[2]} “);

//IF MYSQL RESULT 1 & 2 ARE TRUE THEN PRINTS RECORD INSERTED, ELSE PRINTS ERROR
if($result = “TRUE” && $result2 = “TRUE”) {
echo(” => RECORD INSERTED”);
} else {
echo(” => ERROR”);
}
}
//NEXT ROW
$row++;
}

//CLOSES CSV FILE WHEN COMPLETE
fclose ($handle);

?>
[/code]

I am trying to extract data from a csv file and write it into two different database tables.

I am running into a problem with my mysql_insert_id() command. Does anyone see why this will not work? I am getting the following error:

Warning: mysql_insert_id(): supplied argument is not a valid MySQL-Link resource in /usr/local/www/htdocs/www.ipowerplant.com/excel/index2.php on line 28
Invalid query: You have an error in your SQL syntax near ”company_id’,’last_name’,’list_id’,’subscriber_id’) VALUES(‘A M ‘,’Evans ‘,’40’,’ at line 132/usr/local/www/htdocs/www.ipowerplant.com/excel/index2.php

I ran a debug and I am grabbing all the information from the CSV file fine but for some reason the script is hanging when trying to insert the id from query #1.

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@NogDogMay 13.2005 — You used single-quotes ( ' ) instead of back-ticks ( ` ) around some of the column names. Try changing them all to back-ticks and maybe you'll be OK.
Copy linkTweet thisAlerts:
@ZiplineauthorMay 13.2005 — You were right on NogDog, I copied the query from another script i wrote and forgot to update the quotes. I must have figured it out while you were writing your post.

Also i needed to use addslashes() because some of the users had ' in their names so the script couldn't parse all the addresses. Here is the lastest version for anyone who is looking to parse a CSV file.

[code=php]
<?PHP

//CONFIG VALUES TO SHOW WHICH COMPANY AND EMAIL LIST DATA IS ENTERED FOR
$list_id = "85";
$company_id = "40";

//CONNECTS TO THE MYSQL DATABASE WHERE DATA WILL BE STORED
$link = mysql_connect("localhost", "user","password") or die("Could not connect: ".mysql_error());
$db = mysql_select_db("email_newsletter") or die(mysql_error());

//SETS ROW VALUE OF 1
$row = 1;

//OPENS CSV FILE
$handle = fopen ("good_csv.csv","r");

//PARSES INFORMATION
while ($data = fgetcsv ($handle, 1000, ",")) {

//ONLY SELECTS RECORDS WITH A FIRST NAME, LAST NAME, AND EMAIL
if($data[0] != "" && $data[1] != "" && $data[2] != "") {

$data[0] = addslashes($data[0]);
$data[1] = addslashes($data[1]);
$data[2] = addslashes($data[2]);

//FIRST QUERY INSERTS EMAIL AND LIST INTO SUBSCRIBERS TABLE
$query = "INSERT INTO subscribers(list_id,email) VALUES('".$list_id."', '".$data[2]."')";
$result = mysql_query($query) or die("Invalid query: " . mysql_error().__LINE__.__FILE__);

//GRABS ID FROM QUERY FOR LOYALTYMAX CUSTOMER TABLE
$subscriber_id = mysql_insert_id();

//SECOND QUERY BUILDS CUSTOMER PROFILE IN LOYALTY CUSTOMER DATABASE
$query2 = "INSERT INTO loyaltymax_customer(first_name,email,company_id,last_name,list_id,subscriber_id) VALUES('".$data[0]."','".$data[2]."','".$company_id."','".$data[1]."','".$list_id."','".$subscriber_id."')";
$result2 = mysql_query($query2) or die("Invalid query: " . mysql_error().__LINE__.__FILE__);

//PRINTS EACH RECORD
echo("{$row}. {$data[0]}, {$data[1]}, {$data[2]} ");

//IF MYSQL RESULT 1 & 2 ARE TRUE THEN PRINTS RECORD INSERTED, ELSE PRINTS ERROR
if($result = "1" && $result2 = "1") {
echo(" => RECORD INSERTED <br>");
} else {
echo(" => ERROR <br>");
}
}
//NEXT ROW
$row++;
}

//CLOSES CSV FILE WHEN COMPLETE
fclose ($handle);


?>
[/code]
×

Success!

Help @Zipline spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.15,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...