【问题标题】:PHP MySQLi prepared statement fetch - first row empty?PHP MySQLi准备好的语句提取 - 第一行为空?
【发布时间】:2015-08-12 18:47:14
【问题描述】:

以下代码:

        $con = ConnectDB::getConnection();
    if ($stmt = $con->prepare('---SQL here with 1 param---')) {
        $stmt->bind_param('i', $this->id);
        $stmt->execute();
        $stmt->bind_result($device_id, $device_identifier);

        while ($stmt->fetch()) {
            $device = new Device($device_identifier, $device_id);
            $all_devices[] = $device;
        }

获取一个空结果?第一次通过循环时,$device_id 和 $device_identifier 为空,但 fetch() 方法返回 true,因此它运行。但是 - 第二次迭代实际上包含我的结果。

我可以简单地检查它们是否为空并忽略它们,但我真的不明白为什么它返回一个空对?我尝试直接在数据库上运行 SQL,它只返回 1 个结果行?

有什么想法吗?

【问题讨论】:

  • 你定义了$all_devices = array();吗?

标签: php mysql mysqli prepared-statement


【解决方案1】:

如您所想,MySQLi 准备语句 fetch 不会返回空的第一行。因此,这种行为几乎没有意义。

您需要学习为您的断言创建一个正确证明。
您发布的代码不正确。出于某种原因,您试图通过间接后果来判断事物。 为什么不自己研究一下?

    $con = ConnectDB::getConnection();
if ($stmt = $con->prepare('---SQL here with 1 param---')) {
    $stmt->bind_param('i', $this->id);
    $stmt->execute();
    $stmt->bind_result($device_id, $device_identifier);

    $stmt->fetch();
    var_dump($device_identifier, $device_id);

-- 这段代码会明确地告诉你,你对空结果的假设是对还是错。

了解之后,您可以开始调试,在您自己的代码中找到对当前行为负责的位置。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 2012-12-01
    相关资源
    最近更新 更多