php - fetchAll() 的奇怪行为 - PDO

标签 php mysql pdo

我正在努力解决 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

有人可以帮我理解发生了什么事吗?

最佳答案

好的, friend 们。我现在发现了这个错误,@decez 你完全正确,有一些额外的 echo 语句导致在打印数组后出现 null 。感觉很放松,因为近 12 个小时后我能够成功地继续前进。谢谢大家,特别是@decez。

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

关于php - fetchAll() 的奇怪行为 - PDO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33957295/

相关文章:

php - PDO 在 while 循环内运行查询只显示 1 个结果

php - 简单的 SQL 语句——我应该在这里加入 3 个表还是 2 个?

mysql - 从查询中排除结果

php - 如何从 PHP 访问 Sharepoint 列表?

javascript - 在 javascript 禁用浏览器中提交表单

mysql - Yii2:findOne 查询浮点值的问题

php - 使用 MySQL 获取数据库记录 - 使用 PDO 进行随机行选择

php - 返回 LastInsertID 时 PDO 事务回滚

php - API 输出样式

javascript - html和javascript验证文本框中的密码