0

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

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 {
 (...)

这是最好的方法吗?此代码不可读。我可以使用try catch块而不是if/else if吗?它会运作良好吗?

4

2 回答 2

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 请求,代码已被编辑]

于 2013-04-24T15:13:25.040 回答
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);
}

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

于 2013-04-26T19:28:58.170 回答