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 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'