如何使用PDO与Idiorm检查表是否存在

时间:2017-03-21 17:30:11

标签: php idiorm

/**
 * 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;
}
  1. 如何使用Idiorm PDO配置此功能?
  2. 是否可以使用 -

    try {
        $page = ORM::for_table($table)->where('slug', $slug )->find_one();  
    } (catch $e) {
        // 404 with an error that table does not exists.
    }
    
  3. 而不是“tableExists”功能?

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,您需要检查MySQL数据库中是否存在表格。

Q值。 1

应该注意,这两个查询并不相同。你有:

$page = ORM::for_table($table)->where('slug', $slug )->find_one();

但你的第二个问题应该是:

$page = ORM::for_table($table)->select_expr(1)->find_one();

有关信息,请参阅result columns documentation

Q值。 2

是的,Idiorm在下面使用了PDO,所以你会得到相同的PDO异常 - 这是你真正可以尝试看看它是如何工作的:

try {
    $page = ORM::for_table($table)->where('slug', $slug )->find_one();  
} (catch $e) {
    var_dump($e);
}