PHP MYSQL错误处理 - 预处理语句

时间:2013-04-24 15:04:21

标签: php mysql error-handling

我正在尝试使用预准备语句来实现安全查询:

if (!($stmt = $db->prepare($q['query1']))) {
    myException("Prepare failed: (" . $db->errno . ") " . $db->error);
} else if (!$stmt->bind_param("si", $variable1, $variable2)) {
    myException("Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error);
} else if (!$stmt->execute() || !$stmt->store_result()) {
    myException("Execute failed: (" . $stmt->errno . ") " . $stmt->error);
} else {
 (...)

这是最好的方法吗?此代码无法读取。我可以使用尝试捕获阻止而不是 if / else if 吗?它会运作良好吗?

2 个答案:

答案 0 :(得分:3)

正如您所想,这将更加清晰:

try {
    $stmt = $db->prepare($q['query1']);

    $stmt->bind_param("si", $variable1, $variable2);
    $stmt->bind_param("is", $variable3, $variable4);

    if($stmt->execute()) {
        $stmt->store_result();
        $stmt->bind_result($result);
        $stmt->close();
    } else {
        throw new Exception("error");
    }
} catch (\Exception $e) {
    echo $e->getMessage();
}

[由于OP请求已编辑代码]

答案 1 :(得分:0)

try {
    $stmt = $db->prepare($q['query']);
    $stmt->bind_param("s", $s);
    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($result);

    if ($stmt->fetch()) {
        $stmt->close();
        return $result;
    }
    else
        throw new Exception("error");
} catch (Exception $e) {
    myExceptionHandler($e);
}

你会接受这个代码吗? :)

相关问题