第一个查询中返回的第二个查询的结果

时间:2013-03-27 20:47:39

标签: php mysql mysqli

在我的代码中,我正在检查db中是否存在值。如果它确实存在,则应该返回错误..但是,如果它不存在......它应该在db中创建值。这是我的代码:

/**
 * Check if the string has been used before
 *
 * @return bool
 */
private function _checkStringBeenUsed ()
{
    echo "Running check!\n";

    if ($this->_sString === null) {
        parent::showErrorMessage('Invalid shared String', 1005);
    }

    $this->_validateString();

    $sSql     = "SELECT * FROM operator_string WHERE
                    operatorId = '{$this->_sOperator}' AND
                    sharedString = '{$this->_sString}' AND
                    time >= DATE_SUB(
                        NOW(),
                        INTERVAL 1 DAY
                    )";
    $rQur     = $this->_oDb->query($sSql);

    echo $sSql;
    echo "\n\n";
    echo "Rows: " . $rQur->num_rows;
    echo "\n\n";

    if ($rQur->num_rows > 0) {
        parent::showErrorMessage('Shared string already used', 1005);
    } else {
        $sSql = "INSERT INTO operator_string
                    (operatorId, sharedString, time, hash)
                    VALUES
                    ('{$this->_sOperator}',
                        '{$this->_sString}',
                        NOW(),
                        '{$this->_sHash}'
                    )";
        $this->_oDb->query($sSql);
    }
}

/**
 * Validates the string and the hash
 *
 * @return void
 */
private function _validateString ()
{
    $sHashString = $this->_sOperator . $this->_sSharedSecret . $this->_sString;
    $sHash = hash('sha256', $sHashString);

    if ($sHash != $this->_sHash) {
        parent::showErrorMessage('Invalid authentication hash send', 1006);
    }
}

这是我从iPhone运行命令时的输出:

2013-03-27 21:43:08.560 MyApp[45315:c07] Result: Running check!
SELECT * FROM operator_string WHERE
                        operatorId = 'a8198231u82' AND
                        sharedString = 'cqCEYGIbNvF7HU1' AND
                        time >= DATE_SUB(
                            NOW(),
                            INTERVAL 1 DAY
                        )

Rows: 1

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE error>
<error>
    <errorCode>1005</errorCode>
    <errorMessage>Shared string already used</errorMessage>
</error>

如果在运行呼叫之前表中没有数据,它怎么能是1行?该方法仅运行一次,插入完成 后执行选择。

编辑1
如果我注释掉“插入SQL”行,它就不会向数据库添加任何内容。

1 个答案:

答案 0 :(得分:0)

似乎autocommit默认设置为True。我在mysqli_autocommit($this, false);的子类中使用MySqli将其切换为false,它解决了我的问题。