通过PHP 7.2中的函数访问数据库不起作用

时间:2018-07-30 13:13:49

标签: php jquery function php-7.2

我正在尝试通过一个函数使用一个简单的查询,它无法正常工作,我也不知道为什么。

此代码在函数外部完全正常运行:

$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;

但是,当我将其放置在函数中时,它将停止工作!?

$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;
}

我正准备将PHP 5.5网站升级到7.2,但我不明白我在做什么错,因为以前这样做很好,谢谢。

1 个答案:

答案 0 :(得分:2)

您正在使用函数内部的变量,该变量不存在。您必须像这样传递$mysqli对象变量(和$NEWUSER):

$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;
}

作为旁注,这很奇怪:

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

您可以在php7中解决这个问题

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

或者:

echo $query->fetch_object()->user_name;