douleijiang8111 2012-07-03 15:55
浏览 35
已采纳

PDO连接尝试catch包括

I'm new to PDO and I wanna do it right from the beginning - I'm going to replace my old mysql_ functions on a site.

Have I got it right?:

Should I put the connection code in a try/catch and save it to a file, and include it on top of the page. Then put the queries in try/catch as well.

Or:

Should I put the connection code in a file and include it in the in the top of the try/catch statement above the query?

ver1:

include('pdo.php'); // try/catch in file

try { 

    $stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
    $stmt->execute(array('id' => $id));

    while($row = $stmt->fetch()) {
        print_r($row);
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

ver2:

try {
    include('pdo.php'); // no try/catch in file

    $stmt = $conn->prepare('SELECT * FROM myTable WHERE id = :id');
    $stmt->execute(array('id' => $id));

    while($row = $stmt->fetch()) {
        print_r($row);
    }
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

Or should I put the try/catch in both places?

  • 写回答

1条回答 默认 最新

  • duancan1950 2012-07-03 16:24
    关注

    You should do both and even more :

    • Set an error handler that displays a message to the user and stops the PHP (see set_error_handler)
    • When you initiate the connexion, add a try/catch and throw an error if you catch an exception. Your website won't run without database connection i guess.
    • Do a try/catch around your queries to recover gracefully from error (when you can)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)