INSERT several rows with a prepared statement in a loop

冷暖自知 提交于 2019-12-02 23:37:21

问题


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. ) )


回答1:


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.



来源:https://stackoverflow.com/questions/54325717/insert-several-rows-with-a-prepared-statement-in-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!