简体   繁体   中英

INSERT several rows with a prepared statement in a loop

Sqlserv php error when inserting using array portion

ARRAY PREPRATION

foreach ($data  as $rs) {

 $params []="({$rs->hd},'{$rs->dvn}',{$rs->mth},{$rs->yr},{$rs->stid},{$rs->prcd},'{$rs->prnm}',{$rs->prte},{$rs->ssl},{$rs->clsk},1)";
}

INSERT INTO STATEMENT:

$SqlInsert="insert into  SQl_test (Ss_Hq_cd,Ss_division,Ss_month,Ss_yr,Ss_stk_Id,Ss_prod_cod,Ss_prod_name,ss_prod_rate,Ss_Sale,Ss_Cl_stk,ss_tran_stat) values(?,?,?,?,?,?,?,?,?,?,?) ";
$stmt = sqlsrv_query( $conn, $SqlInsert,$params);

EROOR:

Error in statement preparation/execution.\\n"

Array ( [0] => Array ( [0] => 22018 [SQLSTATE] => 22018 [1] => 245 [code] => 245 [2] => [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Conversion failed when converting the varchar value '(757,'MAIN',12,2018,100899,1250,'xyz',0,100,45,1)' to data type int. [message] => [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Conversion failed when converting the varchar value '(757,'MAIN',12,2018,100899,1250,'xyz',0,100,45,1)' to data type int. ) )

Each array element of $params is just created as a string...

 $params []="({$rs->hd},'{$rs->dvn}',{$rs->mth},{$rs->yr},{$rs->stid},{$rs->prcd},'{$rs->prnm}',{$rs->prte},{$rs->ssl},{$rs->clsk},1)";

You probably meant to create this as an array...

 $params []=[$rs->hd,$rs->dvn,$rs->mth,$rs->yr,$rs->stid,$rs->prcd,$rs->prnm,$rs->prte,$rs->ssl,$rs->clsk,1];

You would then run the INSERT in a loop, pass each array of data one at a time to the query...

$SqlInsert="insert into  SQl_test (Ss_Hq_cd,Ss_division,Ss_month,Ss_yr,Ss_stk_Id,Ss_prod_cod,Ss_prod_name,ss_prod_rate,Ss_Sale,Ss_Cl_stk,ss_tran_stat) values(?,?,?,?,?,?,?,?,?,?,?) ";

foreach ( $params as $param ) {
    $stmt = sqlsrv_query( $conn, $SqlInsert,$param);
}

With mysqli - you would also prepare the INSERT before the loop and just execute it with each row of data in the loop, there is probably a similar thing in SQL Server, but not my area of knowledge.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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