简体   繁体   中英

PDO MYSQL Create table if not exists and find out if it has been created

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM