J.Doe J.Doe - 1 month ago 7
PHP Question

Run PHP query through function

I have this php function

function showfeed($query_){
$query = $con->query($query_);
while ($row=$query->fetch_row()) {
...
}


And this is how i run this function

showfeed("SELECT * FROM uploads WHERE uploads.username = '$NameId' OR uploads.username IN(
SELECT username FROM followers WHERE uploads.username = followers.following)ORDER BY `Date` DESC LIMIT 0,100");


But when i try to run that function i get this error

Call to a member function query() on null

Answer

$con is not defined in the showFeed function's scope.

You should pass $con as an argument to the function

function showFeed($con, $query) {
  $query = $con->query($query);
  ...
}

Or use a global variable

function showFeed($query)
  global $con;
  $query = $con->query($query);
  ...
}

Warning: depending on global variables a lot will make your program really, really bad. You should try to avoid globals as much as possible.

However, in the case of singletons (such as your database connection $con), it is common to use globals. A common workaround is to use a singleton class that might look like this

class Db {
  static private $con;
  static connection() {
    // if no connection exists
    if (!self::$con)
      // store a reference to a new connection here
      // mysqli_connect is an example here; your code might differ for creating $con
      self::$con = mysqli_connect(...);
    // return the connection reference
    return self::$con;
  }
}

Now, because PHP will always allow you to reference the Db class in any function (in the same namespace), you don't have to use the global variables anymore

function showFeed($query) {
  $query = Db::connection()->query($query);
}

In which case it might make sense to make query a static method for your Db class too!

class Db {
  static private $con;
  static public connection() {
    if (!self::$con)
      self::$con = mysqli_connect(...);
    return self::$con;
  }
  static public query($query) {
    // we can get the connection from ourself!
    return self::connection()->query($query)
  }
}

Now your function can be simplified

function showFeed($query) {
  $query = Db::query($query);
}

Of course, you don't want to go overboard with this. I don't know what $con is in your particular example – whatever library/adapter you're using might have some of these things built in. These are just here as examples that help you think about the problem differently.

Comments