douquanhui5735 2015-05-05 07:12
浏览 77
已采纳

使用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);
?>
  • 写回答

1条回答 默认 最新

  • duanrao3371 2015-05-05 07:53
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 SQL Server下载
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求