简体   繁体   English

PHP Forloop遍历数组并将当前数组项插入sql数据库,仅插入一条记录

[英]PHP Forloop loops through an array and insert current array item into sql database, only one record inserting

I have a script that gets data from a database, then loops through the results from the SELECT query by using a forloop and has a query that inserts the array data into another datbase. 我有一个脚本,该脚本从数据库获取数据,然后使用forloop循环遍历SELECT查询的结果,并具有将数组数据插入另一个数据库的查询。 However only the first record gets inserted. 但是,仅插入第一条记录。

I get no errors 我没有错误

Here is the code. 这是代码。

//Get all from job
$getRecords = $connection->prepare("SELECT `CustomerFirstName`,`CustomerLastName`,`CASS_STD_LINE1`,`CASS_STD_LINE2`,`CASS_STD_CITY`,`CASS_STD_STATE`,`CASS_STD_ZIP`,`CustomerCounty`,`CustomerNumber`,`DealNumber`,`TradeIn_1_VIN`,`TradeIn_1_Make`,`TradeIn_1_Model`,`TradeIn_1_Year`,`FrontGross`,`BackGross`,`HoldBackAmount`,`VehicleYear`,`VehicleMake`,`VehicleModel`,`VehicleVIN`,`EntryDate`,`matched`,`notNew` FROM `auth` WHERE `matched` = ?");
$getRecords->execute(array($_POST['jobName']));
$gotRecords = $getRecords->fetchAll(PDO::FETCH_ASSOC);
$getRecords = null;


//Loop Through all records found with matching job name
for($i=0;$i<count($gotRecords); ++$i){
    $rec = $remote->prepare("INSERT INTO `cob_matched_records`(first) VALUES (?)");
    $rec->execute(array($gotRecords[$i]['CustomerFirstName']));

}

The problem with your script is most likely the line 您脚本的问题很可能是该行

$getRecords = null;

destroying the array before the code hits your for-loop. 在代码到达for循环之前销毁数组。
(But that doesn't fit your description "However only the first record gets inserted.". Did you post the actual, unaltered code?) (但是,这不符合您的描述“但是只插入了第一个记录。”。您是否发布了实际的,未更改的代码?)

The point (or one of the points) of prepared statements is that you prepare them once and then execute them multiple times with varying parameters. 准备好的语句的要点(或要点之一)是您准备它们一次,然后使用不同的参数多次执行它们。 So, prepare the INSERT statement once before the loop and then execute it within with the current parameter(s): 因此,在循环之前准备一次INSERT语句,然后在当前参数中执行它:

// assuming PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION, otherwise error handling is missing....
// you might also be interested in http://docs.php.net/manual/en/pdo.begintransaction.php
$stmtSelect = $connection->prepare("SELECT `CustomerFirstName` FROM `auth` WHERE `matched` = ?");
$stmtInsert = $remote->prepare("INSERT INTO `cob_matched_records` (first) VALUES (?)");

$stmtSelect->execute( array($_POST['jobName']) );
foreach( $stmtSelect as $row ) {
    $stmtInsert->execute( array($row['cob_matched_records']) );
}

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

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