Sandhu
Sandhu

Reputation: 836

Running queries through function is making program slow

I am using n number of queries in my program based on php mysql. To shorten the length I defined a query function:

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

and accessing it like on various locations in a same page (obviously with different query):

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

Before implementing this function program was fine, although applying this shorten my code by my page is very slow.

Upvotes: 0

Views: 32

Answers (1)

CollinD
CollinD

Reputation: 7573

Your issue is stemming from opening a new connection every time you call a query! EEK! And it's never closed. You can either remove the "connect()" statement from your function, and make it a separate call. Or, for overall better code flow, switch to MySQLI OOP

I'd recommend moving to mysqli oop. It can be used like so

File: function.php
function getConnection() {
  $mysqli = new mysqli("localhost", "user", "password", "database");
  return $mysqli;
}

And then utilize it in your other files like so

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();

See, here we reuse the same connection. Establishing MySQL connections over and over is a very expensive operation.

Upvotes: 1

Related Questions