By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,264 Members | 1,724 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,264 IT Pros & Developers. It's quick & easy.

uploading txt files,csv files and vcf files into database

P: 7
Hi all i am getting error in the following code to upload files csv and txt files

i have to insert the following values only into database if firstname,lastname and email id is null it should not accept the data and skip that row. And for csv file if encounters headings it should skip that row
the fields are id,firstname,lastname,address,city,state,zip,email ,telephone number

in these above fields firstname,lastname and email should not be null. I wrote the following code the rows with empty values are also getting uploaded. please help me

If any file that doesnt contain any of the above fields it should throw an error

<?php

if(isset($_GET['module']) && !empty($_GET['module']))
{
$module = $_GET['module'];

switch ($module)
{

case 'upload' :
{
$target_path = '';
$csvfilename=$_FILES['userfile']['name'];
$ext = substr(strrchr($csvfilename, '.\.'), 1);
$userid = $_COOKIE["TestCookie"];

if($ext == "csv")
{
$target_path = "temp/". basename( $_FILES['userfile']['name']);

if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['userfile']['name']). " has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
# $skipfirstline = true;
$delimiter = ',';

$handle = fopen($target_path, "r");
if(!$handle) die("unable to find file");

while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
//foreach (array_keys($data) as $v)
//$data[$v] = mysql_real_escape_string($data[$v]);

foreach($data as $values)
{
$values=implode(",",$data);
$value=explode(",",$values);



$a=$value[1];
$b=$value[2];
$c=$value[3];
$d=$value[4];
$e=$value[5];
$f=$value[6];
$g=$value[7];
$h=$value[8];




}

$uploadqry = "insert into ecoup_coupon_subscribers(user_id,firstname,lastnam e,subscriber_address,city,state,zip, email,telephone) values(".$userid.", '" . $a." ','" . $b." ','" . $c." ','" . $d." ','" . $e." ','" . $f." ','" . $g." ','" . $h." ')";

$string= $db->Execute($uploadqry);
if($string===false)
$_SESSION['errMessage'] = "upload failed";
}
fclose($handle);
}elseif($ext == "txt")

{

$target_path = "temp/". basename( $_FILES['userfile']['name']);

//$target_path = $target_path . basename( $_FILES['userfile']['name']);

if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['userfile']['name']). " has been uploaded and emails imported successfully";
} else{
echo "There was an error uploading the file, please try again!";
}

$fcontents = file ($target_path);
$arr = explode(',',$fcontents);
$tmp = array();
$j = 0;
$k = 0;

foreach($fcontents as $k=>$v)
{
$tmp = explode(",",$v);
#echo "<br><br>";
echo $tmp[0]." ";
if ( ($tmp[1] != "") && ($tmp[2] != "") && ($tmp[7] != "") )
{
# echo "valid row";
$uplsubscriber = "insert into ecoup_coupon_subscribers(user_id,firstname,lastnam e,subscriber_address,city,state,zip, email,telephone) values(".$userid.",'".$tmp[1]."','".$tmp[2]."','".$tmp[3]."','".$tmp[4]."','".$tmp[5]."','".$tmp[6]."','".$tmp[7]."','".$tmp[8]."')";
#echo $uploadsubscriber;
#die;
$result = $db->Execute($uplsubscriber);
}
else
{

#echo "Invalid row";
/* $uplsubscriber = "insert into ecoup_coupon_subscribers(user_id,firstname,lastnam e,subscriber_address,city,state,zip, email,telephone) values(".$userid.",'".$tmp[1]."','".$tmp[2]."','".$tmp[3]."','".$tmp[4]."','".$tmp[5]."','".$tmp[6]."','".$arr[7]."','".$tmp[8]."')";
echo $uploadsubscriber;
#die;
$result = $db->Execute($uplsubscriber);*/
}
}

for($i=0; $i<sizeof($fcontents); $i++)
{
$line = trim($fcontents[$i]);
#echo $line;

$arr = explode(",",$line);


foreach ( $arr as $row )
{


if( isset($arr[1]) && $arr[1] != '' && isset($arr[2]) && $arr[2] != '' && isset($arr[7]) && $arr[7] != '')
{
//replace double quotes with empty space

$str = str_replace(" ", "", htmlspecialchars($row[$field_count]));
#echo $str;

#$xtpl->assign("CELL",$str);
#$xtpl->parse("main.table.row.cell");
}

}
$a=trim($arr[1]);
$b=trim($arr[2]);
$c=trim($arr[3]);
$d=trim($arr[4]);
$e=trim($arr[5]);
$f=trim($arr[6]);
$g=trim($arr[7]);
$h=trim($arr[8]);

# print $a;
$uplsubscriber = "insert into ecoup_coupon_subscribers(user_id,firstname,lastnam e,subscriber_address,city,state,zip, email,telephone) values(".$userid.",'".trim($arr[1])."','".trim($arr[2])."','".trim($arr[3])."','".trim($arr[4])."','".trim($arr[5])."','".trim($arr[6])."','".trim($arr[7])."','".trim($arr[8])."')";

$result = $db->Execute($uplsubscriber);
if($result===false)
$_SESSION['errMessage'] = "upload failed";

}

}
$_SESSION['errMessage' ] = 'List uploaded successfully';
unlink($target_path);




}
}

}
function assign ($name,$val="") {
if (gettype($name)=="array")

while (list($k,$v)=each($name))
$this->VARS[$k]=$v;

else
$this->VARS[$name]=$val;
}
?>
<form enctype="multipart/form-data" name="Import" method="POST" action="welcomeuser.php?action=uploadsubscribers&m odule=upload">
<table width="100%" border="0" cellspacing="1" cellpadding="2">
<td>
<table width="100%" border="0" cellspacing="1" cellpadding="6" class="tabForm">

<tr class="mangtableyellow">
<th align="left" class="dataLabel" colspan="4">SELECT FILE TO IMPORT</th>
</tr>
<tr>
<td class="mangtablewhite">
<input type="hidden" />
<input size="60" name="userfile" type="file"/>
</td>
</tr>
<tr class="mangtablewhite">
<td align="left"><input title="IMPORT" accessKey="" class="button" type="submit" name="button" value="Import" onclick="return verify_data(this.form);"></td>

</tr>
</table> </td></table>
</form>
<table> <tr>
<td width="4%"><img src="images/mouse_icon.gif" width="15" height="19"></td>
<td width="96%" class="text4">Please Upload CSV,TXT files only. </td>
</tr>
</table>
Please correct my code and send me. Please help me
Feb 9 '07 #1
Share this Question
Share on Google+
6 Replies


Motoma
Expert 2.5K+
P: 3,235
I haven't looked at your code, because you failed to enclose it in brackets.
I do have a small piece of code that does all of my CSV parsing however:
[PHP]
$handle = fopen($fileName, "r");
$lines = array();
for($i = 0; ($i < $num) && (!feof($handle)); $i++) array_push($lines, fgetcsv($handle,65535));[/PHP]

After that code, $lines will be an array containing the entire CSV.
Feb 9 '07 #2

P: 7
Hi actually whats happening in my following code is when the data in the csv file is updated and uploaded the csv file again, the data is not inserted into the database. please check my code and where i am making mistake please correct my code

thanks in advance

[PHP]
<?php

// connect to DB
$host_name = "localhost";
$db_user = "root";
$db_password = "sachi";
$db_name = "fundgroup";
$table = 'ecoup_coupon_subscribers';

switch ($_POST['act']) {
case 'insert':
$db = mysql_connect("$host_name","$db_user","$db_passwor d") or die("Could not connect to database!");
$result = mysql_select_db($db_name) or die("Could not select database!");

// open file
$fp = fopen($_FILES['userfile']['tmp_name'], 'r') or die('Could not open file!');


while ($data = fgetcsv($fp, 1024))
{
$x=0;
$sql_ = "SELECT * FROM $table ";

$result_=mysql_query($sql_, $db) or die("This selected file Could not contain required fields! Please Select the file again");
$id_=mysql_fetch_row($result_);

if($id_[0]!="") {
// update record in case id was already existed/
$file_content = file($_FILES['userfile']['tmp_name']);
for($i=1; $i<count($file_content); $i++){
echo $file_content[$i].'<br/>';
$varia= explode(",", $file_content[$i]);
if($varia[0]!="" && $varia[1]!="" && $varia[9]!=""){
$update = "UPDATE $table SET firstname='$varia[0]', lastname='$varia[1]',businessstreet='$varia[2]',businessstreet2='$varia[3]',businessstreet3='$varia[4]',businesscity='$varia[5]',businessstate='$varia[6]',businesspostalcode='$varia[7]',businessphone='$varia[8]',email='$varia[9]' WHERE firstname='$varia[0]' ";

$res_update = mysql_query($update, $db) or die("Could not update DB!");
echo "Row #".$num." was updated!<p>";
$num++;
}
}
}
else
{

$file_content = file($_FILES['userfile']['tmp_name']);
for($i=1; $i<count($file_content); $i++){
echo $file_content[$i].'<br/>';
$varia= explode(",", $file_content[$i]);

if($varia[0]!="" && $varia[1]!="" && $varia[9]!=""){

// insert new record into database
$insert = "INSERT INTO $table ( firstname, lastname,businessstreet,businessstreet2,businessst reet3,businesscity,businessstate,businesspostalcod e,businessphone,email)
VALUES('".$varia[0]."','".$varia[1]."','".$varia[2]."','".$varia[3]."','".$varia[4]."','".$varia[5]."','".$varia[6]."','".$varia[7]."','".$varia[8]."','".$varia[9]."')";

echo $insert;
$res_insert = mysql_query($insert, $db) or die("Could not INSERT query!");}
echo "Row #".$num." was inserted!<p>";
$num++;
}
}
if($x>0){
$x++;
}
}


fclose($fp);
break;

default:
echo <<<EOD
<center>
<h3>CSV file upload form</h3>
<form enctype="multipart/form-data" method="POST">
<input type="hidden" name="act" value="insert">
CSV file <input name="userfile" type="file">
<input type="submit" value="Submit">
</form>
</center>
EOD;
break;
}
function validate_CSV( $fileName ) {
$valid = TRUE;
$f = file( $fileName ) or die( "Unable to get file information." );
foreach( $f as $lineNum => $lineContents ) {
if( !preg_match( "/(.*)(,)(.*)/iu", $lineContents ) ) {
echo "Line $lineNum has an error: ($lineContents)<br />";
$valid = FALSE;
}
}
return $valid;
}
?>
[/PHP]
Feb 12 '07 #3

Motoma
Expert 2.5K+
P: 3,235
Hi actually whats happening in my following code is when the data in the csv file is updated and uploaded the csv file again, the data is not inserted into the database. please check my code and where i am making mistake please correct my code

thanks in advance

[PHP]
<?php

// connect to DB
$host_name = "localhost";
$db_user = "root";
$db_password = "sachi";
$db_name = "fundgroup";
$table = 'ecoup_coupon_subscribers';

switch ($_POST['act']) {
case 'insert':
$db = mysql_connect("$host_name","$db_user","$db_passwor d") or die("Could not connect to database!");
$result = mysql_select_db($db_name) or die("Could not select database!");

// open file
$fp = fopen($_FILES['userfile']['tmp_name'], 'r') or die('Could not open file!');


while ($data = fgetcsv($fp, 1024))
{
$x=0;
$sql_ = "SELECT * FROM $table ";

$result_=mysql_query($sql_, $db) or die("This selected file Could not contain required fields! Please Select the file again");
$id_=mysql_fetch_row($result_);

if($id_[0]!="") {
// update record in case id was already existed/
$file_content = file($_FILES['userfile']['tmp_name']);
for($i=1; $i<count($file_content); $i++){
echo $file_content[$i].'<br/>';
$varia= explode(",", $file_content[$i]);
if($varia[0]!="" && $varia[1]!="" && $varia[9]!=""){
$update = "UPDATE $table SET firstname='$varia[0]', lastname='$varia[1]',businessstreet='$varia[2]',businessstreet2='$varia[3]',businessstreet3='$varia[4]',businesscity='$varia[5]',businessstate='$varia[6]',businesspostalcode='$varia[7]',businessphone='$varia[8]',email='$varia[9]' WHERE firstname='$varia[0]' ";

$res_update = mysql_query($update, $db) or die("Could not update DB!");
echo "Row #".$num." was updated!<p>";
$num++;
}
}
}
else
{

$file_content = file($_FILES['userfile']['tmp_name']);
for($i=1; $i<count($file_content); $i++){
echo $file_content[$i].'<br/>';
$varia= explode(",", $file_content[$i]);

if($varia[0]!="" && $varia[1]!="" && $varia[9]!=""){

// insert new record into database
$insert = "INSERT INTO $table ( firstname, lastname,businessstreet,businessstreet2,businessst reet3,businesscity,businessstate,businesspostalcod e,businessphone,email)
VALUES('".$varia[0]."','".$varia[1]."','".$varia[2]."','".$varia[3]."','".$varia[4]."','".$varia[5]."','".$varia[6]."','".$varia[7]."','".$varia[8]."','".$varia[9]."')";

echo $insert;
$res_insert = mysql_query($insert, $db) or die("Could not INSERT query!");}
echo "Row #".$num." was inserted!<p>";
$num++;
}
}
if($x>0){
$x++;
}
}


fclose($fp);
break;

default:
echo <<<EOD
<center>
<h3>CSV file upload form</h3>
<form enctype="multipart/form-data" method="POST">
<input type="hidden" name="act" value="insert">
CSV file <input name="userfile" type="file">
<input type="submit" value="Submit">
</form>
</center>
EOD;
break;
}
function validate_CSV( $fileName ) {
$valid = TRUE;
$f = file( $fileName ) or die( "Unable to get file information." );
foreach( $f as $lineNum => $lineContents ) {
if( !preg_match( "/(.*)(,)(.*)/iu", $lineContents ) ) {
echo "Line $lineNum has an error: ($lineContents)<br />";
$valid = FALSE;
}
}
return $valid;
}
?>
[/PHP]
In this chunk of code, I am only seeing a case for inserting, none for updating.
Please, it is too difficult for me to try and go through your entire block of code, if you could do some cursory debugging and narrow down where your error is happening, or at least write a small sample section which exhibits the same problem, I will be able to help you out much better.
Feb 12 '07 #4

P: 7
Hi
what's happening here is when the email address column before column is null the data is omitted and proceded to further step so i am getting two rows instead of a single row inserted in the page

[PHP]
PHP Code:
1-t_saigopal@yahoo.com
2-saicharan.m@gmail.com
3-rangs.des@yahoo.com
4-ajay.pro@yahoo.com
5-jagadeesh.pro@yahoo.com
6-anil.pro@sachi-infotech.com
7-vbrao@sachi-infotech.com
SELECT * FROM ecoup_coupon_subscribers where Emailaddress=''

PHP Code:
$file_content = file($_FILES['userfile']['tmp_name']);

for($i=1; $i < count($file_content); $i++){
# echo $file_content[$i].'<br/>';
$varia= explode(",", $file_content[$i]);
$sql_ = "SELECT * FROM $table where Emailaddress='".$varia[58]."'";
if($varia[58]==""){
$varia[58]=$varia[57];
echo $i ."-". $varia[58]."<br>";
}
else {
//echo $varia[58];
echo $i ."-". $varia[58]."<br>";
}
// echo $sql_."<br>";
}

echo $sql_;
die();
[/PHP]
Feb 13 '07 #5

Motoma
Expert 2.5K+
P: 3,235
I think you may want to build your SQL select statement after you have figured out what the value of the email address is going to be.
Feb 13 '07 #6

P: 7
yes i am picking the email address from the query to update the record
Feb 13 '07 #7

Post your reply

Sign in to post your reply or Sign up for a free account.