Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I pass my $mysqli variable to each function?

I am having a little problem passing from mysql_* to mysqli object oriented.

My index.php file is structured like including two files:

include('connect.php');
include('function.php');

The connect.php file contains:

<?php
$mysqli = new mysqli("localhost", "root", "test", "test");

if (mysqli_connect_errno($mysqli)) {
    printf("Connection failed: %s\n", mysqli_connect_error());
    exit();
}
?>

In the function.php file there is a function called showPage that takes no arguments but uses the $mysqli connection, in lines like...

$result = $mysqli -> query("SELECT * FROM $table ORDER BY ID DESC"); // Seleziono tutto il contenuto della tabella

I cannot manage it to work without passing to the function the $mysqli variable, but this was not necessary when I used mysql_* deprecated functions!

Can I understand why, and what's the best way to resolve this?

like image 876
wiredmark Avatar asked Dec 24 '12 02:12

wiredmark


1 Answers

User-defined functions have their own variable scope in PHP. You need to pass $mysqli to the function as a parameter, or start the function with global $mysqli.

This exact problem is given as an example on the Variable scope page:

However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example, this script will not produce any output because the echo statement refers to a local version of the $a variable, and it has not been assigned a value within this scope. You may notice that this is a little bit different from the C language in that global variables in C are automatically available to functions unless specifically overridden by a local definition. This can cause some problems in that people may inadvertently change a global variable. In PHP global variables must be declared global inside a function if they are going to be used in that function.

<?php
$a = 1; /* global scope */ 

function test()
{ 
    echo $a; /* reference to local scope variable */ 
} 

test();
?>
like image 129
quietmint Avatar answered Oct 14 '22 00:10

quietmint