2015-05-05 163 views
0

我想逐行閱讀我的文本文件,然後保存到postgresql數據庫。但我得到這些錯誤。保存數據從文本文件PostGreSQL數據庫使用php

"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, ,); ^" 

什麼是錯在我的代碼?這裏是我的示例文本文件:

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\n"; 
} else { 
    echo "Opened database successfully\n"; 
} 
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\n"; 
} 
} 
pg_close($db); 
fclose($fh); 
?> 

回答

0

很顯然你的代碼不插入位置1,3和4的錯誤消息顯示只是逗號的任何數據和任何在兩者之間。在你的代碼有問題的說法是這樣的:

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

添加一些s'es部分1,3和4和一些單引號,你是好:

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

讓你想知道爲什麼PHP不會自帶這個...

+0

@patrick先生?它顯示一個錯誤,如.. 警告:pg_query()[function.pg-query]:查詢失敗:錯誤:列「chung」不存在LINE 2:VALUES(1113,Chung,21,Dimahanap,300000^in C:\ xampp \ htdocs \ phpsave \ index.php第28行 錯誤:列「chung」不存在LINE 2:VALUES(1113,Chung,21,Dimahanap,300000^1114rejie23Dimakita300000 –

+0

這些字符串需要用單引用。我不是PHP專家,所以我不知道該怎麼做。 – Patrick

+0

再次感謝sir @Patrick :)我在每個變量VALUES('$ parts [0]','$ parts [1 ]','$ parts [2]','$ parts [3]','$ parts [4]');它幫助很多:) CHEEEEEEEEEEEERS。 –

相關問題