确定是否已准备好mysqli_result实例?

时间:2016-03-03 23:30:29

标签: php mysqli prepared-statement

是否可以,如果是,那么如何确定是否已准备好mysqli_result的实例?

下面的代码说明了这个问题。在使用mysqli :: stmt_init创建实例并将其传递给某些可能准备或不准备的函数之后,代码应根据是否已准备好进行有条件分支。如果有人知道如何做到这一点,我很想知道。感谢。

function toPrepareOrNotToPrepareThatIsTheQuestion($stmt) {
    if (rand() % 2) {
        $stmt->prepare('DELETE FROM foo WHERE bar = ?');
    }
}

$mysqli = new mysqli($host, $user, $pass, $database);

$stmt = $mysqli->stmt_init();
toPrepareOrNotToPrepareThatIsTheQuestion($stmt);

if ( /* $stmt is not prepared yet */ ) {
    $stmt->prepare('DELETE FROM baz WHERE bar = ?');
}

$stmt->bind_param('i', (int) $bar);
$stmt->execute();

2 个答案:

答案 0 :(得分:1)

PHP documentation for stmt_init个州you can use $stmt = $mysqli->prepare(); directly without stmt-init()的评论。然后它说i think there is no need for stmt-init我更不同意,特别是在你的情况下。

$mysqli = new mysqli($host, $user, $pass, $database);

$stmt = false;

// something could possibly happen here
// which results in $stmt becoming an object via $stmt = $mysqli->prepare()

// $stmt is not set yet
if (!$stmt) {
    $stmt = $mysqli->prepare('DELETE FROM baz WHERE bar = ?');
}

$stmt->bind_param('i', (int) $bar);
$stmt->execute();

答案 1 :(得分:0)

stmt_init的文档说:

  

在调用mysqli_stmt_prepare()之前,对任何mysqli_stmt函数的任何后续调用都将失败。

您可以使用此事实来确定您的陈述是否已准备好。你可以尝试一些无害的(毫无意义,但如果语句准备就不可能失败)调用,如

$is_prepared = $stmt->attr_set(MYSQLI_STMT_ATTR_CURSOR_TYPE, MYSQLI_CURSOR_TYPE_NO_CURSOR);
// MYSQLI_CURSOR_TYPE_NO_CURSOR is the default value.
// Unless you have actually need it to be something else this should have no effect

如果尚未准备好,您将收到警告,$is_prepared将为空,否则将为真。