Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to insert .txt file data into database using php?

I have been inserting .txt file data in my sql-server database using php which is working too but I am getting undefined array error please help me in resolving the same

.txt data

ankit,ankit@gmail.com

swapnil, swapnil@gmail.com

shefali, shefali@gmail.com

abhishek, abhishek@gmail.com

my php code for implementing the same

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?php

include 'connection.php';


$open = fopen('employee.txt','r');

while (!feof($open)) 
{
    $getTextLine = fgets($open);
    $explodeLine = explode(",",$getTextLine);
    
    list($name,$email) = $explodeLine;
    
    $qry = "insert into employees (name,email) values('".$name."','".$email."')";

 $run =     sqlsrv_query($conn,$qry);
}

fclose($open);

?>

// sql table query

CREATE TABLE employees(name VARCHAR(255) ,email VARCHAR(255) );

// Error which i am getting

Warning: Undefined array key 1 in
C:\xampp\htdocs\Mainfileupload\filetesting.php on line 18

Warning: Undefined array key 1 in
C:\xampp\htdocs\Mainfileupload\filetesting.php on line 18

Warning: Undefined array key 1 in
C:\xampp\htdocs\Mainfileupload\filetesting.php on line 18

>Solution :

Better check the line to be "non-blank" before executing query. (e.g. check whether $getTextLine is an empty string first)

So change your while block to

while (!feof($open)) 
{
    $getTextLine = fgets($open);
 
    if (trim($getTextLine)!="") {
      $explodeLine = explode(",",$getTextLine);
      list($name,$email) = $explodeLine;    
      $qry = "insert into employees (name,email) values('".$name."','".$email."')";
      $run = sqlsrv_query($conn,$qry);
     }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading