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.
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.