Reputation: 190
Is there a possibility to ask PDO whether a
CREATE TABLE IF NOT EXISTS
statement actually created a table? I am looking for something similar to check lastInsertID after an INSERT IGNORE statement. If you don't get a result for lastInsertID from PDO, then no data was inserted (because of already existing keys).
Upvotes: 4
Views: 940
Reputation: 34232
Although mysql's documentation is not great on this, the if not exists
clause will result in a mysql warning if the table does exist. Unfortunately, PDO only captures mysql errors, not warnings, so you have to execute a show warnings
sql statement after the create table
and parse its results to check if any warning has been raised:
$warnings = $pdoconn->query("SHOW WARNINGS")->fetchObject();
// example output of $warnings OR NULL
// stdClass Object
// (
// [Level] => Warning
// [Code] => 1050
// [Message] => Table '...' already exists
// )
If no warning is raised that the table already exists and there is no other error raised for the create table
statement, then the table was created as a result of the last create table
.
To be honest, it may be simpler not to use the if not exists
clause and then just use the standard pdo exception handling to capture the mysql error if the table exists. The if not exists
clause was really meant for long sql scripts that do not have proper error handling.
Upvotes: 3