PHP 中奇怪的 for 循环/数组问题

发布于 2024-10-17 12:03:40 字数 1118 浏览 5 评论 0原文

这是我在 StackOverflow 上的第一个问题,坦率地说,我对 PHP 还很陌生。只是为了给您一个简短的提醒;)

我正在构建一个基于 OOP 的网站,采用 3 层架构。在我的数据抽象层中,我有一个名为 DbAdapter 的对象,它包含与数据库通信所需的所有函数。这些函数之一如下:read($sql),它接受 SQL 查询并将结果存储在二维数组中。

为此,它使用两个嵌套的 for 循环(一个用于行,一个用于每行的列)。虽然迭代器 $i 像往常一样递增,但不知何故数组的最后一个元素被覆盖。

我完全不知道这怎么可能,所以我犯的错误一定非常愚蠢。

有人愿意帮助新手吗?

预先感谢,山姆

public $loadedRows;
public function read($sql)
{
    if ($this->connect())
    {
        $result = mysql_query($sql);
        if ($result)
        {
            $totalRows = mysql_num_rows($result);
            $totalFields = mysql_num_fields($result);

            for ($i = 0; $i < $totalRows; $i++)
            {
                for ($j = 0; $j < $totalFields; $j++)
                {
                    $fieldName = mysql_field_name($result, $j);
                    $loadedFields["$fieldName"] = mysql_result($result, $i, $fieldName);
                }

                $this->loadedRows[i] = $loadedFields;
            }

            $this->closeConnection();
            return $this->loadedRows;
        }
    }
}

This is my first question here on StackOverflow, and quite frankly I'm fairly new to PHP. Just to give you a brief heads-up ;)

I'm building an OOP-based website, in a 3-tier architecture. In my data abstraction layer, I have an object I called DbAdapter, which contains all functions necessary to communicate with the database. One of these functions is the one below: read($sql), which takes an SQL query and stores the result in a two-dimensional array.

For this, it uses two nested for-loops (one for the rows and one for the columns per row). And while the iterator $i increments as usual, somehow the last element of the array is overwritten.

I have absolutely no idea how this is possible, so the mistake I made must be extremely stupid.

Anyone care to help out a newbie?

Thanks in advance, Sam

public $loadedRows;
public function read($sql)
{
    if ($this->connect())
    {
        $result = mysql_query($sql);
        if ($result)
        {
            $totalRows = mysql_num_rows($result);
            $totalFields = mysql_num_fields($result);

            for ($i = 0; $i < $totalRows; $i++)
            {
                for ($j = 0; $j < $totalFields; $j++)
                {
                    $fieldName = mysql_field_name($result, $j);
                    $loadedFields["$fieldName"] = mysql_result($result, $i, $fieldName);
                }

                $this->loadedRows[i] = $loadedFields;
            }

            $this->closeConnection();
            return $this->loadedRows;
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

扛起拖把扫天下 2024-10-24 12:03:40

你只是忘记了 i $this->loadedRows[$i] 之前的 $

并且这段代码应该更短:

public function read($sql)
{
    $a = array();
    $result = mysql_query($sql);
    if ($result)
    {
        while($row = mysql_fetch_assoc($res)) $a[]=$row;
    }
    return $a;
}

仅此而已。

要自己捕获这些错误,您应该将错误报告级别设置为 E_ALL
为此,您可以

error_reporting(E_ALL);

在配置文件中添加此行。
它会告诉 PHP 观察此类错误(在本例中使用未定义的常量 i)并通知您

you just forgot $ before i $this->loadedRows[$i]

and this code should be way shorter:

public function read($sql)
{
    $a = array();
    $result = mysql_query($sql);
    if ($result)
    {
        while($row = mysql_fetch_assoc($res)) $a[]=$row;
    }
    return $a;
}

That's ALL.

and to catch these errors yourself, you should set error reporting level to E_ALL
to do that you can add this line

error_reporting(E_ALL);

in your config file.
It will tell PHP to watch such mistakes (using undefined constant i in this case) and notify you

找回味觉 2024-10-24 12:03:40

您不能这样做的任何原因:

while($row = mysql_fetch_assoc()) {
    $this->loadedRows[] = $row;
}

代替您的两个循环?与仅获取已包含字段名/值的关联行相比,像这样单独获取字段名/值的速度非常慢。

就我个人而言,我更喜欢吃一碗麦片,而不是单独从盒子里取出一个,放入碗中,倒一滴牛奶,吃掉它,然后再回到盒子里再拿一个。

Any reason you can't just do:

while($row = mysql_fetch_assoc()) {
    $this->loadedRows[] = $row;
}

In place of both your loops? Fetching fieldnames/values individually like this is hideously slow compared to just fetching a associative row which has the fieldname/values in it already.

Personally, I prefer eating a bowlful of cheerios, rather than individually pulling one from a box, putting it in the bowl, pouring on a drop of milk, eating it, then going back to the box for another one.

抱着落日 2024-10-24 12:03:40

我的猜测是 i 之前缺少的 $ 这是你的罪魁祸首:

           $this->loadedRows[i] = $loadedFields;

My guess is the missing $ before i here is your culprit:

           $this->loadedRows[i] = $loadedFields;
阳光①夏 2024-10-24 12:03:40

如果我是你,我会使用 PDO 而不是这些旧的 mysql 函数。
PDOStatement::fetchAll 可以满足您的需要。

If I were you, I'd use PDO instead of these old mysql functions.
PDOStatement::fetchAll does what you need.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文