简体   繁体   English

循环插入-PHP Postgres插入

[英]Looping through Inserts - PHP Postgres Insert

I am doing inserts via a loop, unfortunately, it seems to insert only a few of the data and ignore some. 我正在通过循环进行插入,很遗憾,似乎只插入了一些数据而忽略了一些。

I'm reading the contents of a file and inserting them into a postgres database using PHP. 我正在读取文件的内容,然后使用PHP将其插入到postgres数据库中。

See my code below. 请参阅下面的代码。

$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';}
?>

I dont see how that would be inserting anything! 我看不到它将插入任何内容!

This line is incorrect 这行是不正确的

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

Correct it to 更正为

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

Also your transaction does not make much sense as it commits every update, which is what would happen if you did not start a transaction. 另外,您的事务没有意义,因为它会提交每次更新,如果不开始事务,则会发生这种情况。 So maybe this would be sensible, and will achieve an all or nothing senario 所以也许这会很明智,并且会实现全有或全无的感觉

In addition, a prepare can be reused many time, so also move that out of the loop, you will find your script runs quicker as well. 此外,准备可以重复使用很多次,因此也可以将其移出循环,您会发现脚本运行得也更快。

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(); 
} 

它有效,问题是由于插入字符串中的未转义字符所致,因此pg_escape_string帮助在插入之前清除了字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM