I'm using PDO in my web application. In a part of this application, I need to work with PDO Transactions. I need to know last inserted id of first query and use it in the second query, and then if no problem occurs, I will commit this transaction.
The problem I have is that how can I find out last inserted id before transaction commit?
This is a sample of my need :
$db->beginTransaction();
$stmt1 = "INSERT ..."; // An insert query
$q = $db->prepare($stmt1);
$q->execute(array());
$last = $db->lastInsertId();
$stmt2 = "UPDATE ..."; // An update query
$q2 = $db->prepare($stmt2);
$q2->execute(array($last));
$db->commit();
Related
I need to get the last inserted ID for each insert operation and put it into array, I am trying to see what is the correct way of doing it.
Following this post Which is correct way to get last inserted id in mysqli prepared statements procedural style?
I have tried to apply it to my code but I am still not getting the right response.
if($data->edit_flag == 'ADDED')
{
$rowdata[0] = $data->location_name;
$rowdata[1] = 0;
$rowdata[2] = $data->store_id;
$query = "INSERT IGNORE INTO store_locations (location_name,total_items, store_id) VALUES (?,?,?)";
$statement = $conn->prepare($query);
$statement->execute($rowdata);
$id = mysqli_stmt_insert_id($statement);
echo "inserted id: " . $id;
}
I then realised that I am using a PDO connection so obviously mysqli functions wont work. I went ahead and tried the following
$id = $conn->lastInsertId();
echo "insert id: " . $id;
but the response is still empty? What am I doing incorrectly? For the lastInsertId(), should I be using $conn or $statement from here:
$statement = $conn->prepare($query);
$statement->execute($rowdata);
You are using lastInsertId() correctly according to the PDO:lastInsertId() documentation
$statement = $conn->prepare($query);
$statement->execute($rowdata);
$id = $conn->lastInsertId();
Some potential reasons why it is not working:
Is this code within a TRANSACTION? If so, you need to COMMIT the transaction after the execute and before the lastInsertId()
Since you INSERT IGNORE there is the potential that the INSERT statement is generating an error and not inserting a row so lastInsertId() could potentially be empty.
Hope this helps!
If you are using pdo,
$stmt = $db->prepare("...");
$stmt->execute();
$lastInsId = $db->lastInsertId();
Here is my script:
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
try{
$db_conn->beginTransaction();
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
$db_conn->commit();
}
catch(PDOException $e){
$db_conn->rollBack();
}
All I want to know, can I use an if statement in the codes which are between beginTransaction() and commit() ? Something like this:
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
try{
$db_conn->beginTransaction();
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
if (/* a condition here */){
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
}
$db_conn->commit();
}
catch(PDOException $e){
$db_conn->rollBack();
}
Can I ?
Actually I asked that because here is a sentence which says you can't and doing that is dangerous:
Won't work and is dangerous since you could close your transaction too early with the nested commit().
There is no problem with your transaction structure. The comment on php.net only means, that MySQL does not support nested transactions. In order to your further question, you can query any data (SQL), manipulate data (DML), but not modify any database structures (DDL - data definition language).
/*won't work*/
START TRANSACTION;
/*statement*/
START TRANSACTION; /*nested not supported, auto commit*/
/*statement*/
COMMIT;
/*statement dependend on 1st transaction won't work*/
COMMIT;
See also MySQL ref
Transactions cannot be nested. This is a consequence of the implicit commit performed for any current transaction when you issue a START TRANSACTION statement or one of its synonyms.
You can do everything within a transaction, the only thing you cannot do is nest transactions.
Not the if clause itself is the problem in your linked comment, but the fact there is another beginTransaction / commit pair inside.
I am trying to get the id of the last record inserted in an mssql database using pdo via php. I HAVE read many posts, but still can't get this simple example to work, so I am turning to you. Many of the previous answers only give the SQL code, but don't explain how to incorporate that into the PHP. I honestly don't think this is a duplicate. The basic insert code is:
$CustID = "a123";
$Name="James"
$stmt = "
INSERT INTO OrderHeader (
CustID,
Name
) VALUES (
:CustID,
:Name
)";
$stmt = $db->prepare( stmt );
$stmt->bindParam(':CustID', $CustID);
$stmt->bindParam(':Name', $Name);
$stmt->execute();
I have to use PDO querying an MSSQL database. Unfortunately, the driver does not support the lastinsertid() function with this database. I've read some solutions, but need more help in getting them to work.
One post here suggests using SELECT SCOPE_IDENTITY(), but does not give an example of how incorporate this into the basic insert code above. Another user suggested:
$temp = $stmt->fetch(PDO::FETCH_ASSOC);
But, that didn't yield any result.
If your id column is named id you can use OUTPUT for returning the last inserted id value and do something like this:
$CustID = "a123";
$Name="James"
$stmt = "INSERT INTO OrderHeader (CustID, Name)
OUTPUT INSERTED.id
VALUES (:CustID, :Name)";
$stmt = $db->prepare( stmt );
$stmt->bindParam(':CustID', $CustID);
$stmt->bindParam(':Name', $Name);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result["id"]; //This is the last inserted id returned by the insert query
Read more at:
https://msdn.microsoft.com/en-us/library/ms177564.aspx
http://php.net/manual/es/pdo.lastinsertid.php
I try to make prepared statament using pdo. It is possible to put several updates atonce?
Ex:
sql1 = "Update product set large = '1large' where id = 1";
sql2 = "Update product set large = '2large' where id = 2";
sql3 = "Update product set large = '3large' where id = 3";
How to prepare sql1,sql2....sqlN in Pdo to execute faster?
I found an example but it works line by line (sql1, sql2 ....)
<?php
$stmt = $dbh->prepare("UPDATE product SET large = ':large' WHERE id = ':id'");
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$stmt->bindParam(':large', $large, PDO::PARAM_STR);
$stmt->execute();
?>
Unlike inserts, which can be grouped into a single statement, updates are specific to an existing entry in the database.
Dependant on the broader context of what you are doing you may find a question like this of interest for bulk updates using CASE, WHEN, THEN:
Question: Update multiple rows with one query?
I have a mysql transaction with three queries
In the third query I am trying to pull last_insert_id values from the two previous queries.
VALUES ('".$result1[last_id]."','".$result2[last_id]."')";
But it doesn't work. Any suggestions?
You should get the last insert ID first, and then inject it into the query. Assuming you're using the mysql_ functions:
mysql_query($query1);
$id1 = mysql_insert_id();
mysql_query($query2);
$id2 = mysql_insert_id();
$query3 = "INSERT INTO ... VALUES (".$id1.", ".$id2.");";
mysql_query($query3);
Assuming that you are using MySQL database. You can get id like:
mysql_query($first_query);
$first_result_id = mysql_insert_id();
mysql_query($second_query);
$second_result_id = mysql_insert_id();
$third_query = "INSERT INTO table (column1, column2) VALUES (".$first_result_id .", ".$second_result_id .");";
mysql_query($third_query);
Hope this helps
You can use MySQL to
SELECT LAST_INSERT_ID()
which will retrieve the last insert ID in the given transaction. You can also do this in other DBMS, but you are obviously using MySQL.
Since you are, the MySQL APIs in php have shortcuts for this too:
//mysql_*
$id = mysql_insert_id();
//PDO
$pdo = PDO_OBJECT;
$pdo->query();
$id = $pdo->lastInsertId();
//mysqli
$my = MYSQLI_OBJECT;
$my->query();
$id = $my->insert_id;
NOTE: #HopeIHelped's answer is misleading. There is no race condition as long as you are within the same transaction. LAST_INSERT_ID() retrieves the last ID in the given transactions (and the APIs above do as well), so even if you have this file running a ton of transactions and interlocking queries at once, you can use them safely.