3

I was just asking myself what is faster: I have a for loop where I have to check a certain table column against my loop variable.

Now I have two options: Within the loop I fire a query for each iteration and check my results. The second option is to fetch all the rows I need, and within my for-loop I run a foreach-loop and check if I have a valid match between my desired field and my loop variable.

It's a bit hard to explain but I just let the code speak. I don't use real code here within the loops but fictional function calls by way of illustration.

Option 1: Querying the database for each iteration.

<?php

// Option 1:

for($i = 0; $i < 5; $i++)
{
    $query_result = query_database_where_field_equals($i);
    if($query_result)
    {
        echo "Here is something";
    }
    else
    {
        echo "Here is nothing";
    }

}

// Option 2:

$results = query_database_and_get_all_results();

for($i = 0; $i < 5; $i++)
{

    foreach($results AS $result)
    {
        if($result['desired_field'] == $i)
        {
            echo "Here is something";
        }
        else
        {
            echo "Here is nothing";
        }
    }

}

?>

Both ways will work, but I'm pretty sure it's a worse practice to fire queries within a loop in a performant point of view.

But using a foreach loop within the for-loop also seems to be a bit odd to me.

So what is the prefered way of doing this?

Edit - Added information

I have a for loop that needs to run several times. The amount is static (e.g. 5) and does not depend on any records in the database. Each iteration represents a position.

I have a database table which might store information about what a position contains.

Example:

positions (id, position)

So an example record might be: positions (1, 2)

That means that I have something on position 2. What I want to do in my loop basically is, to check whether I got a record for that position or not. Expected output would be:

Here is nothing
Here is nothing
Here is something
Here is nothing
Here is nothing
4

3 回答 3

1

前面两个答案都是正确的。
@Euantorano:代码迭代优于查询。您将避免较慢的数据库访问,并且您将避免数据库过载。
不过,正如 Slaks 所说,您可以添加 WHERE 条件,这会减少您的数组。在循环中提高性能以检查存在。

最后,我建议使用单个 bucle 来索引结果,这样您就可以检查结果是否已设置。

$res = array();
$results = query_database_and_get_all_results();
for($results as $r) {
    $res[$result['desired_field']] = $r;
}
for($i = 0; $i < 5; $i++) {
    echo (isset($res[i]) ? "Here is something" : "Here is nothing");
}

此代码根据数组的大小 + 您的第二个 bucle 为您提供恒定的性能。根据您的需要,更好的查询实际上可以带来更好的性能,但这取决于您的具体问题。
希望能帮助到你!

于 2013-06-19T18:28:23.990 回答
1

第二个选项是两个给定选项中的首选,但了解更多关于您正在循环和查询的确切内容的信息可能会帮助您获得更好的答案。

于 2013-06-19T16:03:58.947 回答
1

两者都不。

您应该将循环放入查询中,使用WHERE field IN (0, 1, 2, 3, 4)

于 2013-06-19T16:02:06.933 回答