Like the title says, I want the id of a row to be returned after INSERT to the database.
I’ve got 2 functions, one to make a connection to the database:
function db_connect() { $host = "host"; $user = "user"; $pwd = "pwd"; $database = "db"; $con; try{ $conn = new PDO( "sqlsrv:Server= ".$host." ; Database = ".$database." ", $user, $pwd); } catch(Exception $e){ die(print_r($e)); } return $conn; }
And one to insert a new record:
function setTiptile($name,$cols,$rows) { $connect = db_connect(); $query = "INSERT INTO data(ID, name, cols, rows) VALUES(NEWID(),?,?,?)"; $stmt = $connect->prepare($query); $stmt->bindValue(1, $name); $stmt->bindValue(2, $cols); $stmt->bindValue(3, $rows); $stmt->execute(); return $connect->lastInsertId('ID'); // This should work, but doesn't, why? }
I need the last function to return the ID of the inserted row, how should I do this?
EDIT: Like the title says, the ID is an uniqueidentifier, no idea if that changes things.
EDIT: Ok, apparently I’ve got to use:$connect->lastInsertId('ID');
, but this isn’t returning anything at all. What can be the cause of that? The new row ís created in the database.
Advertisement
Answer
(My) solution:
The parameter of lastInsertId() has to be the table name instead of the row name. Besides that, the table must have a row with the parameter IDENTITY checked, this is the row which is returned.
That brings to the conclusion that it’s impossible to return a uniqueidentifier with lastInsertId() since this cannot have the parameter IDENTITY checked.