473,320 Members | 2,145 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

uploading txt files,csv files and vcf files into database

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
6 4075
Motoma
3,237 Expert 2GB
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
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
3,237 Expert 2GB
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
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
3,237 Expert 2GB
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
yes i am picking the email address from the query to update the record
Feb 13 '07 #7

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

Similar topics

4
by: ayanwen | last post by:
I have problem in uploading files using ASP, can you give me some sample code about uploading using ASP? -- ayanwen ------------------------------------------------------------------------...
1
by: Gary | last post by:
Hi all, I am trying to upload file (>500 MB in size) from my webform. Bandwidth is not a issue as the asp.net application would be used in the Intranet environment. Can someone plz suggest...
13
by: Sky Sigal | last post by:
I have created an IHttpHandler that waits for uploads as attachments for a webmail interface, and saves it to a directory that is defined in config.xml. My question is the following: assuming...
4
by: Himanshu | last post by:
hi, Can anybody tell me that thru asp.net using c#, how can we upload and download physical files in any table of SQL Server Database. the uploading part is running successfully but the...
4
by: Kevin D. | last post by:
I have a web application that continues to "break" on me after a random amount of time. There doesn't appear to be a rhyme or reason, just out of nowhere some of my error handling kicks in and...
5
by: Chris | last post by:
I have a meetings section I'm developing on our intranet. Using PHP/MySQL. Meeting info and Meeting docs reside on 2 related tables in the db. Users may want to upload anywhere from 1 to 10 or...
1
by: rajarameshvarma | last post by:
Hi.. I am facing problems with file uploading in asp.net.my filea are nearly 40 MB size. I set the MaxRequestLength property to match. Files are getting uploaded but it is taking so much time. I...
221
Atli
by: Atli | last post by:
You may be wondering why you would want to put your files “into” the database, rather than just onto the file-system. Well, most of the time, you wouldn’t. In situations where your PHP application...
5
by: chromis | last post by:
Hi, I'm trying to figure out the best method for uploading a number of files along with entering some data into a database using a component containing CRUD methods. I have the following file...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.