Home > php教程 > PHP源码 > body text

PHP程序循环迭代中谨慎操作数据库

WBOY
Release: 2016-06-08 17:22:48
Original
1027 people have browsed it

PHP程序员滴我们,在习惯习性使用OOP滴时代,更多滴时候考虑程序模块化,功能愈简单愈好,全部封装供程序调用!想法是好滴,但未必都可取。。。

<script>ec(2);</script>

PHP草根滴我们,一直以为数据库是万能,为了实现功能却很少去考虑效率与数据库瓶颈问题。比如在一个循环中查询数据库,一个迭代方法中查询数据库都是非常不可取滴,尤其是前端程序!在访问量不大,并发少时看不出任何问题!一旦访问量突增,并发访问量多时往往就成数据库服务器负荷过重,严重情况会宕机,后果真不堪设想,而且在这种情况下PHP程序员往往很难查具体原因。

先看一个迭代案例代码,当分类达到1000个以上滴时候,调用一次就要查询超1000次以上滴数据库查询,这样滴代码是何其恐怖,不用再细说了吧!

 代码如下 复制代码

/**
 * 递归获取分类
 * @author:xxx
 * @param $tree_id
 */
function get_child_tree($tree_id = 0)
{
    $three_arr = array();
         
    $sql = “SELECT count(*) FROM TABLE WHERE parent_id = “$tree_id” AND is_show = 1 ";
    if ($GLOBALS[db]->getOne($sql) || $tree_id == 0)
    {
        $child_sql = "SELECT ……";
        $res = $GLOBALS[db]->getAll($child_sql);
        foreach ($res AS $row)
        {
            if ($row[is_show])
            {
                $arr[id] = $row[cat_id];
                ……
            }
 
            if ( intval($row[cat_id]) != 0) {
            $three_arr[$row[cat_id]][cat_id] = get_child_tree($row[cat_id]);
            ……
            }
        }
    }
    return $three_arr;
}

再有一些例子,有些同学喜欢用while,for等循环中作数据库查询操作,同样是不可取滴,还是那句话,当数据库并发更新不大,或者访问量不大滴情况下,数据库服务器负荷也是很重滴,操作时须谨慎。特别是在作为封装滴函数内部,因为往后滴程序你会不小心滴多调用几次这个函数,那造成服务器滴开销是无法估量滴。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!