I have the following Query:
$Query = "INSERT INTO table (name, bio) VALUES ('aname', `abio`)";
$stmt = $conn->prepare($Query);
$stmt->execute();
$last_id = $stmt->lastInsertId();
$Query = "INSERT INTO table2 (tid, papers) VALUES ($last_id, '1') ON DUPLICATE KEY UPDATE papers = '2'";
$stmt = $conn->prepare($Query);
$stmt->execute();
table
has the aname, abio : unique
, and table2
has tid, papers : unique
The user is supposed to INSERT
a name
and bio
, If it is already exists or not, they insert the papers
to the table2
with the id
of the inserted name, bio
, The problem that if the name, bio
already exists, I don't get the $last_id
How can I pull the id
of the duplicated row When PDO tells me that that thre is a Dupicate?
I'm assuming that this
How can I pull the id of the duplicated row When PDO tells me that that thre is a Dupicate
Means you have a unique field set on the table.
I would do something like this:
try{
$Query = "INSERT INTO table (name, bio) VALUES ('aname', `abio`)";
$stmt = $conn->prepare($Query);
$stmt->execute();
$last_id = $stmt->lastInsertId();
}catch(PDOExeption $e){
if($e->getCode() != 23000){ //I think it's 23000
//rethrow other PDO errors
throw new PDOException(
$e->getMessage(),
$e->getCode(),
$e
);
}
$Query = "SELECT id FROM table WHERE name = 'aname'";
$stmt = $conn->prepare($Query);
$stmt->execute();
//fetch the first column (id) from the first row, which if its unique there will be only one.
$last_id = $stmt->fetchColumn(0);
}
$Query = "INSERT INTO table2 (tid, papers) VALUES ($last_id, '1') ON DUPLICATE KEY UPDATE papers = '2'";
$stmt = $conn->prepare($Query);
$stmt->execute();
You may have to turn the error mode for PDO to exception if you haven't done so already.
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
But basically you catch the duplicate exception thrown by PDO, then you take the unique field, I'm using name
because you didn't say what it was. Then take the value that failed an look it up by that. It stands to reason if you have a unique field and a value failed then the row you want has the same value. Then you set $last_id
. So last id get's set by lastInsertId or by the catch block.
P.S. I didn't test any of this so sorry if there are any errors, but the theory is sound.