doujuchuan9915 2014-12-06 07: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 07: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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部