简体   繁体   中英

PHP, MSSQL, SQLSRV (prepared) driver; How do I get the ID of the row I've just inserted?

I'm looking to produce the last inserted id using SQLSRV. I need to use a prepared statement though. I've seen an answer on here (see link after the code below) showing how to do it, but the statement isn't prepared for anti-sql injection purposes.

//Prep the variables for insert
$p1 = $_POST['description'];
$p2 = intval($_POST['visible']);
$p3 = strval($_POST['whoToShow']);

//Build an array with those variables
$params = array(&$p1, &$p2, &$p3);

//Build the SQL
$sql = "INSERT INTO notifications (description, visible, whoToShow) VALUES (?, ?, ?)";

//Execute the sql using a prepared statement, passing the variables in an array
$stmt = sqlsrv_prepare($conn, $sql, $params) or die(FormatErrors(sqlsrv_errors())); 

Please review Microsoft´s sqlsrv driver for PHP not returning any result when querying "SELECT SCOPE_IDENTITY() AS id" on Stack Overflow for details on getting the last inserted ID using a non prepared statement.

Thank you in advance for your support.

Consider using a stored procedure instead of a direct INSERT statement. Using a stored procedure is better as you can return a recordset from the stored procedure which would include the ID of the inserted record.

I'm using Microsoft SQL Server with my PHP. I am using the mssql_query library to connect to SQL server. Not sure if it makes a difference, but I see you're using a different library to connect. Every query we do is through stored procedures. Its far more efficient and definitely more secure.

$myServer = "xxxxxxx";
$myUser = "xxxxxxxx";
$myPass = "xxxxxxx";
$myDB = "myDatabase";
//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");

$query = "exec eCommerce.dbo.cart_GET_Detail    @sid = ".$_SESSION['sid']." , @cc = '".$_SESSION['cc']."'";

$result = mssql_query($query);
$numRows = mssql_num_rows($result);
$hasItems = (($numRows == 0) ? 'N' : 'Y');

while ($RSLoop = mssql_fetch_array($result)) {
    //var_dump($RSLoop);  //var_dump will show you everything in the recordset
    echo '<tr><td colspan=6 width=720 class=cartDivider>&nbsp;</td></tr>';
    echo '<form name=frmProduct'.$idx.' method=POST action=_action.asp>';
    echo '<input type=hidden name=pid value="'.$RSLoop['product_id'].'">';
}

That was a call to a stored procedure to get the contents of the shopping cart stored in a SQL table. Doing an insert on a stored procedure is similar. You should be able to find some code samples on SQL Server stored procedures.

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