小智 36
这是一个检查表是否存在的完整函数.
/**
* Check if a table exists in the current database.
*
* @param PDO $pdo PDO instance connected to a database.
* @param string $table Table to search for.
* @return bool TRUE if table exists, FALSE if no table found.
*/
function tableExists($pdo, $table) {
// Try a select statement against the table
// Run it in try/catch in case PDO is in ERRMODE_EXCEPTION.
try {
$result = $pdo->query("SELECT 1 FROM $table LIMIT 1");
} catch (Exception $e) {
// We got an exception == table not found
return FALSE;
}
// Result is either boolean FALSE (no table found) or PDOStatement Object (table found)
return $result !== FALSE;
}
Run Code Online (Sandbox Code Playgroud)
注意:PDO只会在被告知时抛出异常,默认情况下它是静默的并且不会抛出异常.这就是我们为什么需要检查结果的原因.请参阅php.net上的PDO错误处理
Nat*_*use 11
在继续之前,我确实意识到这是一个特定于MySQL的解决方案.
虽然这里提到的所有解决方案都可行,但我(个人)希望让PDO不要抛出异常(个人偏好,就是这样).
因此,我使用以下内容来测试表创建:
SHOW TABLES LIKE 'some_table_of_mine';
Run Code Online (Sandbox Code Playgroud)
如果表不存在则不会生成错误状态,只需获得零结果集.对我来说,快速而持续地工作.
Mil*_*kov 10
做:
select 1 from your_table
Run Code Online (Sandbox Code Playgroud)
然后发现错误.如果您没有收到任何错误,但结果集中包含一个包含"1"的列,则该表存在.