2016-12-13 105 views
0

我正在通过循环插入,不幸的是,它似乎只插入了一些数据并忽略了一些。循环插入 - PHP Postgres插入

我正在读取文件的内容并使用PHP将它们插入到postgres数据库中。

看到我的代码如下。

$source='/Users/gsarfo/AVEC_ETL/TCCDec052016OSU.DAT'; 

$lines=file($source); 

$len =sizeof($lines); 

$connec = new PDO("pgsql:host=$dbhost;dbname=$dbname", $dbuser, $dbpwd); 

$ins=$connec->query('truncate table tbl_naaccr_staging'); 

try { 

    for ($x = 0; $x < $len; $x++) { 
     $a1=substr($lines[$x],146,9); 
     $a2=substr($lines[$x],2182,9); 
     $a3=substr($lines[$x],192,3); 
     $connec->beginTransaction(); 

     $sql2=$connec->prepare("INSERT INTO tbl_naaccr_staging 
           (addr,name, email) VALUES (?, ?, ?"); 

     $sql2->execute(array($a1, $a2, $a3)); 
     $connec->commit();  
    } 
    $res=$connec->query($sql) ; 
} 

catch (PDOException $e) { 
    echo "Error : " . $e->getMessage() . "<br/>"; 
    die(); 
} 

if ($sql2) 
{echo 'success';} 
?> 
+0

所有这些空格不会使你的代码的任何更具可读性 – RiggsFolly

回答

0

它的工作,问题是由于在字符串转义字符插入使pg_escape_string帮助清理之前要插入的字符串

1

我不知道怎么会插入任何东西!

这行不正确

$sql2=$connec->prepare("INSERT INTO tbl_naaccr_staging 
         (addr,name, email) VALUES (?, ?, ?"); 
                 ^^ here 

纠正它

$sql2=$connec->prepare("INSERT INTO tbl_naaccr_staging 
         (addr,name, email) VALUES (?, ?, ?)"); 

而且您的交易并没有多大意义,因为它承诺每次更新,这是如果你没有启动,会发生什么交易。所以也许这会是明智的,并且会实现全部或者没有任何变化。另外,一个准备可以重复使用很多次,所以也把它移出循环,你会发现脚本的运行速度也更快。

try { 

    $connec->beginTransaction(); 

    // move this out of the loop 
    $sql2=$connec->prepare("INSERT INTO tbl_naaccr_staging 
          (addr,name, email) VALUES (?, ?, ?)"); 

    for ($x = 0; $x < $len; $x++) { 
     $a1=substr($lines[$x],146,9); 
     $a2=substr($lines[$x],2182,9); 
     $a3=substr($lines[$x],192,3); 

     $sql2->execute(array($a1, $a2, $a3)); 
    } 
    $connec->commit(); 

    // I do not see a `$sql` variable so this query seems to have no function 
    //$res=$connec->query($sql) ; 
} 

catch (PDOException $e) { 
    $connec->rollback();  

    echo "Error : " . $e->getMessage() . "<br/>"; 
    die(); 
}