0

I keep getting this error and can't figure out why: "PHP Fatal error: Call to a member function query() on null"

All my mysqli calls work except within a function.

My connection.php file has:

$connection = new mysqli("localhost", "user", "pass", "db");

I've tried setting $connection as a global thinking this was a scope problem, but it's still a thing.

include('connection.php');

function text($x) {
  $query = "SELECT * FROM content WHERE page='". $x ."'";
  $result = $connection->query($query)->fetch_assoc();
  return $result['column'];
}
test('home');

Querying outside of functions works fine.

Xatenev
  • 6,274
  • 3
  • 16
  • 42
dstana
  • 312
  • 2
  • 9

2 Answers2

0

You should declare you variable $connection as global, to use it inside your function:

include('connection.php');

function text($x) {
  global $connection;
  $query = "SELECT * FROM content WHERE page='". $x ."'";
  $result = $connection->query($query)->fetch_assoc();
  return $result['column'];
}
test('home');
Ass3mbler
  • 3,539
  • 2
  • 19
  • 17
  • this is usually bad practice, https://stackoverflow.com/questions/5166087/php-global-in-functions –  Jan 30 '19 at 00:12
  • @Tim, I agree, but I'm answering his question respecting the prototype of his function – Ass3mbler Jan 30 '19 at 00:14
  • I cant see how answering, with you agree is bad practice, is helpful to the OP –  Jan 30 '19 at 00:16
  • It's easy, because his question is not about good practices, but about how to make his code work while it's not working, and his prototype doesn't have a second parameter. If he want to use a bad practice, he may have his reasons for doing it, like (in example) avoiding to refactor an existing codebase. So if it's possible to answer without forcing such a change, it should be done :) – Ass3mbler Jan 30 '19 at 00:22
  • 1
    @tim This answer is redundant, as is the "bad practice" meme. Having *one single* "global" var for the db connection has never killed anyone. – mario Jan 30 '19 at 00:22
  • the solutions listed in the link i provided make much more sense than this one. calling it a meme is disingenuous, its not as if ther are no alternatives. –  Jan 30 '19 at 00:59
  • What is the best way in this case? Create a new $connection object in the function? – dstana Jan 30 '19 at 01:30
0

It would be better to pass the $connection variable as parameter.

include('connection.php');

function text($x, $connection) {
  $query = "SELECT * FROM content WHERE page='". $x ."'";
  $result = $connection->query($query)->fetch_assoc();
  return $result['column'];
}
test('home',$connection);
smavroud
  • 125
  • 4