使用pdo try / catch从函数返回值

时间:2014-12-06 15:13:58

标签: php pdo

我有一个像这样的PHP函数:

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
    }
}

如果查询成功并且没有异常,则该函数不应该返回TRUE吗?

获取上述函数的唯一方法是返回TRUE,如果我修改“try”部分:

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

我错过了什么?

1 个答案:

答案 0 :(得分:0)

引用the documentation

  

如果省略返回值,则返回NULL值。

由于NULL在大多数情况下被评估为false,因此答案为否,除非明确声明,否则此函数不会返回TRUE。 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;
}
相关问题