uploading txt files,csv files and vcf files into database

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ajaykataram
    New Member
    • Jan 2007
    • 7

    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,lastn ame 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,la stname,address, city,state,zip, email,telephone number

    in these above fields firstname,lastn ame 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_uploade d_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_p ath, "r");
    if(!$handle) die("unable to find file");

    while (($data = fgetcsv($handle , 1000, $delimiter)) !== FALSE)
    {
    //foreach (array_keys($da ta) as $v)
    //$data[$v] = mysql_real_esca pe_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_su bscribers(user_ id,firstname,la stname,subscrib er_address,city ,state,zip, email,telephone ) values(".$useri d.", '" . $a." ','" . $b." ','" . $c." ','" . $d." ','" . $e." ','" . $f." ','" . $g." ','" . $h." ')";

    $string= $db->Execute($uploa dqry);
    if($string===fa lse)
    $_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_uploade d_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(',',$fc ontents);
    $tmp = array();
    $j = 0;
    $k = 0;

    foreach($fconte nts 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_su bscribers(user_ id,firstname,la stname,subscrib er_address,city ,state,zip, email,telephone ) values(".$useri d.",'".$tmp[1]."','".$tmp[2]."','".$tmp[3]."','".$tmp[4]."','".$tmp[5]."','".$tmp[6]."','".$tmp[7]."','".$tmp[8]."')";
    #echo $uploadsubscrib er;
    #die;
    $result = $db->Execute($uplsu bscriber);
    }
    else
    {

    #echo "Invalid row";
    /* $uplsubscriber = "insert into ecoup_coupon_su bscribers(user_ id,firstname,la stname,subscrib er_address,city ,state,zip, email,telephone ) values(".$useri d.",'".$tmp[1]."','".$tmp[2]."','".$tmp[3]."','".$tmp[4]."','".$tmp[5]."','".$tmp[6]."','".$arr[7]."','".$tmp[8]."')";
    echo $uploadsubscrib er;
    #die;
    $result = $db->Execute($uplsu bscriber);*/
    }
    }

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

    $arr = explode(",",$li ne);


    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(" ", "", htmlspecialchar s($row[$field_count]));
    #echo $str;

    #$xtpl->assign("CELL", $str);
    #$xtpl->parse("main.ta ble.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_su bscribers(user_ id,firstname,la stname,subscrib er_address,city ,state,zip, email,telephone ) values(".$useri d.",'".trim($ar r[1])."','".trim($a rr[2])."','".trim($a rr[3])."','".trim($a rr[4])."','".trim($a rr[5])."','".trim($a rr[6])."','".trim($a rr[7])."','".trim($a rr[8])."')";

    $result = $db->Execute($uplsu bscriber);
    if($result===fa lse)
    $_SESSION['errMessage'] = "upload failed";

    }

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




    }
    }

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

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

    else
    $this->VARS[$name]=$val;
    }
    ?>
    <form enctype="multip art/form-data" name="Import" method="POST" action="welcome user.php?action =uploadsubscrib ers&module=uplo ad">
    <table width="100%" border="0" cellspacing="1" cellpadding="2" >
    <td>
    <table width="100%" border="0" cellspacing="1" cellpadding="6" class="tabForm" >

    <tr class="mangtabl eyellow">
    <th align="left" class="dataLabe l" colspan="4">SEL ECT FILE TO IMPORT</th>
    </tr>
    <tr>
    <td class="mangtabl ewhite">
    <input type="hidden" />
    <input size="60" name="userfile" type="file"/>
    </td>
    </tr>
    <tr class="mangtabl ewhite">
    <td align="left"><i nput title="IMPORT" accessKey="" class="button" type="submit" name="button" value="Import" onclick="return verify_data(thi s.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">P lease Upload CSV,TXT files only. </td>
    </tr>
    </table>
    Please correct my code and send me. Please help me
  • Motoma
    Recognized Expert Specialist
    • Jan 2007
    • 3236

    #2
    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($lin es, fgetcsv($handle ,65535));[/PHP]

    After that code, $lines will be an array containing the entire CSV.

    Comment

    • ajaykataram
      New Member
      • Jan 2007
      • 7

      #3
      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_s ubscribers';

      switch ($_POST['act']) {
      case 'insert':
      $db = mysql_connect(" $host_name","$d b_user","$db_pa ssword") 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_fetc h_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='$var ia[0]', lastname='$vari a[1]',businessstree t='$varia[2]',businessstree t2='$varia[3]',businessstree t3='$varia[4]',businesscity= '$varia[5]',businessstate ='$varia[6]',businessposta lcode='$varia[7]',businessphone ='$varia[8]',email='$varia[9]' WHERE firstname='$var ia[0]' ";

      $res_update = mysql_query($up date, $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,busine ssstreet,busine ssstreet2,busin essstreet3,busi nesscity,busine ssstate,busines spostalcode,bus inessphone,emai l)
      VALUES('".$vari a[0]."','".$vari a[1]."','".$vari a[2]."','".$vari a[3]."','".$vari a[4]."','".$vari a[5]."','".$vari a[6]."','".$vari a[7]."','".$vari a[8]."','".$vari a[9]."')";

      echo $insert;
      $res_insert = mysql_query($in sert, $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="multip art/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]

      Comment

      • Motoma
        Recognized Expert Specialist
        • Jan 2007
        • 3236

        #4
        Originally posted by ajaykataram
        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_s ubscribers';

        switch ($_POST['act']) {
        case 'insert':
        $db = mysql_connect(" $host_name","$d b_user","$db_pa ssword") 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_fetc h_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='$var ia[0]', lastname='$vari a[1]',businessstree t='$varia[2]',businessstree t2='$varia[3]',businessstree t3='$varia[4]',businesscity= '$varia[5]',businessstate ='$varia[6]',businessposta lcode='$varia[7]',businessphone ='$varia[8]',email='$varia[9]' WHERE firstname='$var ia[0]' ";

        $res_update = mysql_query($up date, $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,busine ssstreet,busine ssstreet2,busin essstreet3,busi nesscity,busine ssstate,busines spostalcode,bus inessphone,emai l)
        VALUES('".$vari a[0]."','".$vari a[1]."','".$vari a[2]."','".$vari a[3]."','".$vari a[4]."','".$vari a[5]."','".$vari a[6]."','".$vari a[7]."','".$vari a[8]."','".$vari a[9]."')";

        echo $insert;
        $res_insert = mysql_query($in sert, $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="multip art/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.

        Comment

        • ajaykataram
          New Member
          • Jan 2007
          • 7

          #5
          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@yaho o.com
          2-saicharan.m@gma il.com
          3-rangs.des@yahoo .com
          4-ajay.pro@yahoo. com
          5-jagadeesh.pro@y ahoo.com
          6-anil.pro@sachi-infotech.com
          7-vbrao@sachi-infotech.com
          SELECT * FROM ecoup_coupon_su bscribers where Emailaddress=''

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

          for($i=1; $i < count($file_con tent); $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]

          Comment

          • Motoma
            Recognized Expert Specialist
            • Jan 2007
            • 3236

            #6
            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.

            Comment

            • ajaykataram
              New Member
              • Jan 2007
              • 7

              #7
              yes i am picking the email address from the query to update the record

              Comment

              Working...