使用插入语句时,使用数组会产生错误

时间:2019-01-23 11:01:10

标签: php sqlsrv

使用数组操作插入时,sqlserv php eoor

阵列准备

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

插入语句:

$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);

色情:

  

语句准备/执行中的错误。\ n“

     

Array([0] => Array([0] => 22018 [SQLSTATE] => 22018 [1] => 245 [代码] => 245 [2] => [Microsoft] [ODBC Driver for SQL服务器] [SQL Server]将varchar值'(757,'MAIN',12,2018,100899,1250,'xyz',0,100,45,1)'转换为数据类型int时转换失败。[message] => [Microsoft] [用于SQL Server的ODBC驱动程序13] [SQL Server]将varchar值'(757,'MAIN',12,2018,100899,1250,'xyz',0,100,45,1)'转换为时,转换失败数据类型为int。))

1 个答案:

答案 0 :(得分:0)

$params的每个数组元素都只是创建为字符串...

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

您可能打算将其创建为数组...

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

然后您将循环运行INSERT,一次将每个数据数组一次传递给查询...

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

使用mysqli-您还可以在循环之前准备INSERT并只对循环中的每一行数据执行它,SQL Server中可能有类似的事情,但是我所不擅长的领域。