0

I'm trying to use a simple query though a function, it is not working and I have no clue why.

This code woks perfectly outside a function:

$mysqli = new mysqli($db_hostname, $db_username, $db_password, $db_database);
$NEWUSER = "jack";

$query = $mysqli->query("SELECT user_name FROM Users WHERE user_name = '$NEWUSER'");
$result = implode("",$query->fetch_assoc());
echo $result;

However when I place it in a function it ceases to work!?

$mysqli = new mysqli($db_hostname, $db_username, $db_password, $db_database);
$NEWUSER = "jack";

someFunction();

function someFunction() {
    $query = $mysqli->query("SELECT user_name FROM Users WHERE user_name = '$NEWUSER'");
    $result = implode("",$query->fetch_assoc());
    echo $result;
}

I'm woking on upgrading my PHP 5.5 site to 7.2 and I don't understand what am I doing wrong because this worked just fine previously, thanks.

1 Answers1

2

You are working with a variable inside the function, which does not exist. You must pass the $mysqli object variable (and $NEWUSER) in like so:

$mysqli = new mysqli($db_hostname, $db_username, $db_password, $db_database);
$NEWUSER = "jack";

someFunction($NEWUSER,$mysqli);
//              ^--------^---- note passing it in along with the NEWUSER var

function someFunction($NEWUSER,$mysqli) {
//                       ^--------^---- define them for pass-in
    $query = $mysqli->query("SELECT user_name FROM Users WHERE user_name = '$NEWUSER'");
    $result = implode("",$query->fetch_assoc());
    echo $result;
}

As a side note, this is very odd:

$result = implode("",$query->fetch_assoc());
echo $result;

You can get away with just this in php7:

echo $query->fetch_assoc()['user_name'];

Or:

echo $query->fetch_object()->user_name;
IncredibleHat
  • 4,000
  • 4
  • 15
  • 27
  • ah, I did't realize that I had to pass all variables though. My assumption was any variable outside the function would wok in the function like in JS. THANKS! – Stewart MacLean Jul 30 '18 at 13:37
  • Correct. This gets a bit different in a class, where you can keep the db object in a class variable and access it directly in methods inside that class. But an example of that was a bit much to add :) Whatever you do, DONT succumb to just using `global` everywhere ;) – IncredibleHat Jul 30 '18 at 13:42