doujuchuan9915 2014-12-06 15:13
浏览 69
已采纳

使用pdo try / catch从函数返回值[关闭]

I have a php function much like this:

function add($db, $value) { 
    try {
    $stmt = $db->prepare("INSERT INTO table(value) VALUES (?);");
    $stmt->execute(array($value));
}
catch(PDOException $e) {
    error_log($e->getMessage());
         // Error handeling
    }
}

If the query is successfull and there is no exception, shouldn't the function return TRUE?

The only way to get the function above return TRUE is if I modify the "try" section:

if ($stmt->execute(array($value))) {
return TRUE;
   }

What am I missing?

  • 写回答

1条回答 默认 最新

  • dsdzz04802 2014-12-06 15:21
    关注

    To quote the documentation:

    If the return is omitted the value NULL will be returned.

    Since NULL is evaluated as false in most contexts, then the answer is no, this function will not return TRUE unless you explicitly state it. E.g.:

    function add($db, $value) { 
        try {
            $stmt = $db->prepare("INSERT INTO table(value) VALUES (?);");
            if ($stmt->execute(array($value))) {
                return TRUE;
            }
        }
        catch(PDOException $e) {
            error_log($e->getMessage());
            // Error handeling
        }
        // If we got here, the execute did not succeed
        return FALSE;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度