2014-12-09 56 views
2

我有這段代碼將在我的表上插入一些數據,並且我需要獲取最後插入的ID,這是我的PK。使用PHP在SQL Server上插入的最後一個值

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

我已經嘗試過SELECT @@IDENTITY但它只返回resource(4) of type (SQL Server Statement)

+2

使用SCOPE_IDENTITY() – HaveNoDisplayName 2014-12-09 13:18:24

+0

@Jordy,對不起,我沒有找到!謝謝:) – Terkhos 2014-12-09 13:33:18

回答

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

Reference:

+0

工作就像一個魅力。謝謝 – Terkhos 2014-12-09 13:31:32

+0

@Terkhos,如果我的答案適合您,請接受它作爲解決方案。 – Pupil 2014-12-09 13:32:15

+0

對不起,忘了! – Terkhos 2014-12-09 14:35:32

-1

這工作:

select last_insert_id() as last_id 
+0

它是SQL而不是MySQL – Peter 2014-12-09 13:20:34