简体   繁体   中英

Retrive Param from SQL SERVER Query on PHP

I'm having a really annoying problem with a simple query.

So:

INSERT INTO [SapuV2].[dbo].[ALERGIA] ([DESCRIPCION]) OUTPUT INSERTED.PK_ALERGIA VALUES ('test')

PK_ALERGIA is a primary identity key, and i need the new id created.

PHP code:

$sql = "INSERT INTO ALERGIA (DESCRIPCION) OUTPUT INSERTED.PK_ALERGIA VALUES(?)";
$id = 0;
$params = array(
  array(&$nombre, SQLSRV_PARAM_IN),
  array(&$id, SQLSRV_PARAM_OUT, SQLSRV_PHPTYPE_INT)
);
$stmt = sqlsrv_prepare($this->Conn, $sql, $params);
if( sqlsrv_execute($stmt) === false){
  die( print_r( sqlsrv_errors(), true) );
}else{
  var_dump($id);
}

I'm able to save records on my BD, but $id is always 0 ...

Thanks ;)

请尝试以下方法:

INSERT INTO ALERGIA (DESCRIPCION)select @var=scope_identity()

I finally did it, but i'm not proud ...

Using same SQL Query, but change the sqlsrv_execute to a sqlsrv_fetch_array

$sql = "INSERT INTO ALERGIA ([DESCRIPCION]) OUTPUT INSERTED.PK_ALERGIA VALUES (?)";
$params = array(
  array(&$nombre, SQLSRV_PARAM_IN)
);
$rows = sqlsrv_query($this->Conn, $sql, $params);
if($rows === false){
  die(var_dump(sqlsrv_errors()));
}else{
  while($row = sqlsrv_fetch_array($rows, SQLSRV_FETCH_ASSOC)){
    var_dump($row);
  }
}

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