通过函数运行查询会使程序变慢


Running queries through function is making program slow

我在基于php mysql的程序中使用n个查询。为了缩短长度,我定义了一个查询函数:

FILE: function.php
function myquery($query){
        $connection  = connect();
        $result = mysqli_query($connection,$query);
        return $result;
    }

并像在同一页面的不同位置访问它一样(显然使用不同的查询):

    FILE: index.php
    $result = myquery("SELECT itemName, mfrName, itemid,
              openingstock, conversion, reOrderQty FROM items ORDER BY itemName ASC;");

在实现这个函数之前程序很好,尽管应用这个缩短我的代码到我的页面是非常慢的

您的问题源于每次调用查询时打开一个新连接!唷!它从来没有关闭过。您可以从函数中删除"connect()"语句,并将其作为单独的调用。或者,为了总体上更好的代码流,切换到MySQLI OOP

我推荐使用mysqloop。它可以这样使用

File: function.php
function getConnection() {
  $mysqli = new mysqli("localhost", "user", "password", "database");
  return $mysqli;
}
然后在其他文件中使用它,比如
File: index.php
$mysql = getConnection();
$mysql->query("Select STUFF FROM PLACES");
//blah blah later in the file
$mysql->query("Another more different query!");
//end of file
$mysql->close();

看,这里我们重用了相同的连接。反复建立MySQL连接是非常昂贵的操作