Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用pdo try/catch从函数返回值_Php_Pdo - Fatal编程技术网

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

Php 使用pdo try/catch从函数返回值,php,pdo,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 hande

我有一个类似以下内容的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”部分:

我遗漏了什么?

引用:

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

由于
NULL
在大多数上下文中被计算为false,那么答案是no,除非您显式地声明,否则此函数将不会返回
TRUE
。例如:

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

你现在的问题是什么?我的问题是:函数不应该返回true吗?我的问题是“if”部分是否真的应该是nessasary。函数不应该返回TRUE吗?如果您不做return语句,默认值为
null
!(是的,您需要if,因为代码可能“成功”,但查询可能失败),从“catch”部分返回一些有用的信息以指示失败可能会很有用。”再次抛出错误通常是明智的。
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;
}