dsxz84851 2017-03-21 17:30 采纳率: 100%
浏览 62
已采纳

如何使用PDO与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. How to configure this function with Idiorm PDO?
  2. Is it okey to use -

    try {
        $page = ORM::for_table($table)->where('slug', $slug )->find_one();  
    } (catch $e) {
        // 404 with an error that table does not exists.
    }
    

instead of the "tableExists" function?

  • 写回答

1条回答 默认 最新

  • doubi3996 2017-03-21 23:30
    关注

    If I am understanding your question correctly you want to check if a table exists in a MySQL database.

    Q. 1

    It should be noted that the two queries are not identical. You've got:

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

    But your second query should be:

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

    See the result columns documentation for information.

    Q. 2

    Yes, Idiorm uses PDO underneath so you'll get the same PDO exception - this is something you really could just try and see how it works with:

    try {
        $page = ORM::for_table($table)->where('slug', $slug )->find_one();  
    } (catch $e) {
        var_dump($e);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图