我希望检查在使用PHP和PDO连接的数据库中是否存在一个特定名称的表格。
它必须适用于所有数据库后端,如MySQL、SQLite等。
以下是检查表是否存在的完整函数。
/**
* 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;
}
在我继续之前,我确实意识到这是一种针对MySQL的特定解决方案。
虽然这里提到的所有解决方案都可能有效,但我(个人而言)喜欢让PDO不抛出异常(只是个人喜好)。
因此,我使用以下内容来测试表创建:
SHOW TABLES LIKE 'some_table_of_mine';
如果表不存在,不会生成错误状态,而是只会得到一个零结果集。对我来说,工作速度快且一致。
应该做:
select 1 from your_table
然后捕获错误。如果没有出现任何错误,但结果集中只包含一个值为“1”的列,则该表存在。
一旦你通过PDO获取了数据库句柄,你可以这样做:
$tableExists = gettype($dbh->exec("SELECT count(*) FROM $table")) == 'integer';
或者将其包装在一个函数中。
起初我尝试用try/catch来解决问题,但即使表不存在,也没有异常。最后我检查了dbh exec调用返回值的数据类型。如果在select count上有匹配(即使计数为0),它是一个整数,否则就是false的布尔值,表示没有结果。
我认为这对PDO支持的所有数据库类型都适用,因为语法非常简单。
SELECT TABLE_NAME FROM ALL_TABLES
对于Mysql:
SELECT TABLE_NAME FROM information_schema.tables WHERE table_schema = 'mydbname'
然后在您的代码中对该视图运行查询。
起初,我使用了被接受的答案,但后来发现在空表格时会失败。这是我现在正在使用的代码:
function DB_table_exists($db, $table){
GLOBAL $db;
try{
$db->query("SELECT 1 FROM $db.$table");
} catch (PDOException $e){
return false;
}
return true;
}
$q = $pdo->query("SHOW TABLES LIKE '{$table}'");
$tableExists = $q->fetchColumn();
SHOW TABLES
的等价物)。 - David Timothy Strausstry{
//Your major statements here
}
catch(PDOException $e){
if($e->errorInfo[1] == 1146){
//when table doesn't exist
}
}
$e->getCode()
。 - leopold这个完整的函数与esbite的答案非常相似,但包括保护免受SQL注入攻击的代码。此外,当涉及的表为空时,您可能无法从接受的答案中获得一致的结果。
/**
* This function checks if the table exists in the passed PDO database connection
* @param PDO $pdo - connection to PDO database table
* @param type $tableName
* @return boolean - true if table was found, false if not
*/
function tableExists(PDO $pdo, $tableName) {
$mrSql = "SHOW TABLES LIKE :table_name";
$mrStmt = $pdo->prepare($mrSql);
//protect from injection attacks
$mrStmt->bindParam(":table_name", $tableName, PDO::PARAM_STR);
$sqlResult = $mrStmt->execute();
if ($sqlResult) {
$row = $mrStmt->fetch(PDO::FETCH_NUM);
if ($row[0]) {
//table was found
return true;
} else {
//table was not found
return false;
}
} else {
//some PDO error occurred
echo("Could not check if table exists, Error: ".var_export($pdo->errorInfo(), true));
return false;
}
}
$table = preg_replace('/[^\da-z_]/i', '', $table);
。该代码可以对$table
变量进行过滤,并保留其中的数字、大小写字母和下划线字符,其他字符将被移除。 - rybo111