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

Time:09-28

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,[email protected]

swapnil, [email protected]

shefali, [email protected]

abhishek, [email protected]

my php code for implementing the same

<?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

CodePudding user response:

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);
     }
}

CodePudding user response:

That warning issue represent to pass array variable at sqlsrv_query method & also remove unnecessary blank line at employee.txt

$qry = "INSERT INTO employees (name, email) values(?, ?)";
$params = [$name, $email];
$run = sqlsrv_query( $conn, $qry, $params);
if( $run === false ) {
    die( print_r( sqlsrv_errors(), true));
}

For more reference, please check link https://www.php.net/manual/en/function.sqlsrv-query.php

  •  Tags:  
  • php
  • Related