Question

A PHP page say, common.php contains the line, with some other PHP variables and code.

$mysqli=new MySQLi("localhost", "username", "password");

So in the other pages, I simple include this common.php, using require_once("common.php") and use the $mysqli variable for all database related operations. Everything works fine. In a random situation, I need to create a function inside a PHP page such as,

function checking($some_data)
{
  // Using $mysqli check $some_data with database here and return 0 or 1 based on database operations
  // Here it says $mysqli is not defined.
}

$somevariable=$mysqli->prepare($query); // This is outside the function and works fine
$result=checking($some_data); // This does not work and says $mysqli not defined.

I tried adding global $mysqli inside the function. But if I do that, MySQLi connection is not available for that. Defining $mysqli inside each and every function with connection parameters, sound insane. What may be the simple solution?

Was it helpful?

Solution

Adding global $mysqli inside the function will work pretty in this case. If it does not work, you are doing a mistake somewhere in your function or in the query(may be).

function function_name_here($arguement_variable_here)
{
  global $mysqli;
  $mysqli->query($query);
}

And make sure, you include the dependency file - common.php before the function definition. If the include/require is done below the function(s) definition, probably that may not work in some cases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top