使用PHP在SQL Server上最后插入的值
我有这个代码,它将在我的表中插入一些数据,我需要得到最后一个插入的ID,即我的PK使用PHP在SQL Server上最后插入的值,php,sql,Php,Sql,我有这个代码,它将在我的表中插入一些数据,我需要得到最后一个插入的ID,即我的PK $serverName = "MyServer"; $connectionInfo = array( "Database"=>"MyBD", "UID"=>"MyUser", "PWD"=>"MyPass"); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $co
$serverName = "MyServer";
$connectionInfo = array( "Database"=>"MyBD", "UID"=>"MyUser", "PWD"=>"MyPass");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn )
{
echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$nome = $_POST["nome"];
$email = $_POST["email"];
$telefone = $_POST["telefone"];
$unidade = $_POST["unidade"];
//declare the SQL statement that will query the database
$query = "INSERT INTO [dbo].[Participante] ([nome],[email],[telefone],[unidadeCE],[dataCadastro]) VALUES ('" . $nome . "', '" . $email . "', '" . $telefone . "', '" . $unidade . "', (getdate())); SELECT @@IDENTITY";
//execute the SQL query and return records
$result = sqlsrv_query($conn, $query);
var_dump($result);
//close the connection
sqlsrv_close($conn);
$serverName=“MyServer”;
$connectionInfo=array(“数据库”=>“MyBD”、“UID”=>“MyUser”、“PWD”=>“MyPass”);
$conn=sqlsrv_connect($serverName,$connectionInfo);
如果($conn)
{
回显“已建立连接。
”;
}
其他的
{
echo“无法建立连接。
”;
模具(打印错误(sqlsrv_errors(),true));
}
$nome=$_POST[“nome”];
$email=$_POST[“email”];
$telefone=$_POST[“telefone”];
$unidade=$_POST[“unidade”];
//声明将查询数据库的SQL语句
$query=“插入[dbo]。[Participante]([nome]、[email]、[telefone]、[unidadeCE]、[dataCadastro])值(“$nome.”、“$email.”、“$telefone.”、“$unidade.”、“(getdate());选择@标识”;
//执行SQL查询并返回记录
$result=sqlsrv_查询($conn,$query);
var_dump($结果);
//关闭连接
sqlsrv_close($conn);
我已经尝试过选择@@IDENTITY
,但它只返回类型为(SQL Server语句)的资源(4)
此操作有效:
select last_insert_id() as last_id
使用SCOPE\u IDENTITY()@Jordy,对不起,我没找到!谢谢:)工作得很有魅力。Thanks@Terkhos,如果我的答案对你有用,请接受它作为解决方案。对不起,忘了!
$query = "INSERT INTO [dbo].[Participante] ([nome],[email],[telefone],[unidadeCE],[dataCadastro]) VALUES ('" . $nome . "', '" . $email . "', '" . $telefone . "', '" . $unidade . "', (getdate())); SELECT SCOPE_IDENTITY()";
$resource=sqlsrv_query($conn, $query, $arrParams);
sqlsrv_next_result($resource);
sqlsrv_fetch($resource);
echo sqlsrv_get_field($resource, 0);