使用php将数据从文本文件保存到PostGreSQL数据库

I want to read my text file line by line and then save to the postgresql database.But I got these ERRORS.

"Warning: pg_query() [function.pg-query]: Query failed: ERROR: syntax error at or near "," LINE 2: VALUES (1113, , 21, , ); ^ in C:\xampp\htdocs\phpsave\index.php on line 28
ERROR: syntax error at or near "," LINE 2: VALUES (1113, , 21, , ); ^1114rejie23Dimakita300000 

Warning: pg_query() [function.pg-query]: Query failed: ERROR: syntax error at or near "," LINE 2: VALUES (1114, , 23, , ); ^ in C:\xampp\htdocs\phpsave\index.php on line 28
ERROR: syntax error at or near "," LINE 2: VALUES (1114, , 23, , ); ^1115James24Dimakita2300000

Warning: pg_query() [function.pg-query]: Query failed: ERROR: syntax error at or near "," LINE 2: VALUES (1115, , 24, , ); ^ in C:\xampp\htdocs\phpsave\index.php on line 28
ERROR: syntax error at or near "," LINE 2: VALUES (1115, , 24, , ); ^"

What's wrong in my code ? Here is my sample text file:

image

<?php
$host        = "host=localhost";
$port        = "port=5432";
$dbname      = "dbname=sample";
$credentials = "user=postgres password=12345";

$fh = fopen('C:/Users/DecryptDcode/Desktop/james.txt','r');

$db = pg_connect("$host $port $dbname $credentials");
 if(!$db){
  echo "Error : Unable to open database
";
} else {
  echo "Opened database successfully
";
}
 while (!feof($fh) ) {
    $line_of_text = fgets($fh);
    $parts = explode('|', $line_of_text);
    print $parts[0] . $parts[1]. $parts[2] . $parts[3].  $parts[4]. "<BR>";
    $sql =<<<EOF
     INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
     VALUES ($parts[0], $part[1], $parts[2], $part[3], $part[4]);
    EOF;
  $ret = pg_query($db, $sql);
   if(!$ret){
     echo pg_last_error($db);
  } else {
  echo "Records created successfully
";
 }
}
pg_close($db);
fclose($fh);
?>

Quite obviously your code does not insert any data in positions 1, 3 and 4. The error message shows just commas and nothing in between. The offending statement in your code is this:

INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
  VALUES ($parts[0], $part[1], $parts[2], $part[3], $part[4]);

Add a few s'es in part 1, 3 and 4 and some single-quotes and you are good:

INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
  VALUES ($parts[0], '$parts[1]', $parts[2], '$parts[3]', $parts[4]);

Makes you wonder why PHP wouldn't bring this up by itself...