MySQLi准备if语句

时间:2014-08-03 17:33:26

标签: php mysql sql mysqli

我有一个奇怪的错误。以下代码:

$stmt = $mysqli->prepare("SELECT sold FROM Sales WHERE unitId = ? AND date = ?");
$stmt->bind_param('is', $unitId, $date);
$stmt->execute();
$stmt->bind_result($col1);
if ( $stmt->fetch() ) {
    // If something was fetched, it has already uploaded a value today so we need to update it
    echo "Existed!";
    $update = $mysqli->prepare("UPDATE Sales SET sold = ? WHERE unitId = ? AND date = ?");
    var_dump($update);
} else {
    // It hasn't been inserted yet, so insert the new record
    echo "Not here man?!";
}

说$ update是false,因此带有更新SQL的预准备语句没有返回对象。

但是,如果我将该部分放在代码之前,例如:

    $stmt = $mysqli->prepare("SELECT sold FROM Sales WHERE unitId = ? AND date = ?");
$update = $mysqli->prepare("UPDATE Sales SET sold = ? WHERE unitId = ? AND date = ?");
var_dump($update);
$stmt->bind_param('is', $unitId, $date);
$stmt->execute();
$stmt->bind_result($col1);
if ( $stmt->fetch() ) {
    // If something was fetched, it has already uploaded a value today so we need to update it
    echo "Existed!";
} else {
    // It hasn't been inserted yet, so insert the new record
    echo "Not here man?!";
}

那么它有效吗?现在var_dump说$ update是一个对象。

为什么我不能在获取后执行此操作?我是否需要立即准备所有陈述?我相信我在这里缺少一些基本的东西,这就是我要问的原因。

希望有人可以澄清。 谢谢

修改


我明白了!在准备另一个声明之前,我需要调用free_result。但是,我不知道为什么,所以我将这个问题留待澄清。这段代码有效,现在我只需知道原因:

    $stmt = $mysqli->prepare("SELECT sold FROM Sales WHERE unitId = ? AND date = ?");
$stmt->bind_param('is', $unitId, $date);
$stmt->execute();
$stmt->bind_result($col1);
if ( $stmt->fetch() ) {
    $stmt->free_result();

    // If something was fetched, it has already uploaded a value today so we need to update it
    $update = $mysqli->prepare("UPDATE Sales SET sold = ? WHERE unitId = ? AND date = ?");
    $update->bind_param('dis', $amount, $unitId, $date);
    if ( $update->execute() )
        echo "Success";
    else
        echo "Failure";
} else {
    // It hasn't been inserted yet, so insert the new record
    echo "Not here man?!";
}

0 个答案:

没有答案