【问题标题】:Weird behavior of fetchAll() - PDOfetchAll() 的奇怪行为 - PDO
【发布时间】:2015-11-27 12:19:12
【问题描述】:

我正在为 fetchAll() 的奇怪行为而苦苦挣扎。我正在使用返回歌曲集的 PDO 执行存储过程。

这是我的 PHP 代码

    $sql = "call getHymn(?)";
    $param = array($id);
    $result = $this->db->getData($sql,$param);

这里是getData 函数

public function getData($sql,$param=[])
{
    try
    {
        $stmt = $this->connection->prepare($sql);
        $stmt->execute($param);
        echo '<pre>';
        print_r($stmt->fetchAll());
        /*return($stmt->fetchAll());*/
    }
    catch (PDOException $e)
    {
        throw new Exception($e->getMessage());
    }
}

当我在 MySQL 中执行存储过程时,它会按预期返回 3 行。但是,当我通过 PDO 执行它并使用 fetchall() 时,我会在数组之外得到额外的 null ..在任何地方都找不到任何帮助,甚至在 PHP 文档中也找不到。我的 fetchAll() 输出如下所示

Array
(
[0] => Array
    (
        [id] => 4
        [refrain] => 
        [stanzaId] => 1
        [stanzaText] => Amazing grace! How sweet the sound 
that saved a wretch like me! 
I once was lost, but now am found; 
was blind, but now I see.
    )

[1] => Array
    (
        [id] => 4
        [refrain] => 
        [stanzaId] => 2
        [stanzaText] => 'Twas grace that taught my heart to fear, 
and grace my fears relieved; 
how precious did that grace appear 
the hour I first believed.
    )

[2] => Array
    (
        [id] => 4
        [refrain] => 
        [stanzaId] => 3
        [stanzaText] => Through many dangers, toils, and snares, 
I have already come; 
'tis grace hath brought me safe thus far, 
and grace will lead me home
    )
)
null

这是我的存储过程,非常简单直接

CREATE DEFINER=`root`@`localhost` PROCEDURE `getHymn`(IN `hid` INT)
    READS SQL DATA
BEGIN
    select 
        a.id, a.refrain, b.stanzaId, b.stanzaText 
    from 
        hymns a, hymnstanza b 
    where a.id = hid and a.id = b.hymnid;
END

谁能帮我理解发生了什么?

【问题讨论】:

  • 您的表格行是否包含引号?
  • 由于 null 不是结果集的一部分,它根本不可能是 PDO 的输出,而只是源自代码中一些完全不相关的部分。
  • 我不知道我应该在这里误读什么。你的输出显示Array ( .. ) nullprint_r 肯定不会输出数组后跟null。这些是在代码中两个不同位置输出的两个单独的值。此外,如果您将 @ 提及放在 ` 反引号中,我们将不会收到通知。
  • return 语句真的被评论了吗?
  • 你在使用that fetchAll bug 所指的the CSV reader class 吗?看起来你不是来自你的源代码?

标签: php mysql pdo


【解决方案1】:

好的,朋友们。我现在发现了这个错误,@decez 你是绝对正确的,有一些额外的 echo 语句导致 null 在打印数组后出现。在将近 12 小时后,我感到非常放松,我能够成功地继续前进。谢谢大家,尤其是@decez。

为了详细说明我犯了什么错误,我对 fetchAll() 的输出进行了双重 JSON 化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    相关资源
    最近更新 更多