致命错误:在第 219 行的 admin.php 中的非对象上调用成员函数 query()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21245040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:57:08  来源:igfitidea点击:

Fatal error: Call to a member function query() on a non-object in admin.php on line 219

phpmysqlifatal-error

提问by TomFirth

I've searched a lot of basically the same questions on SO which haven't seemed to help. Been a while since i've touched php so i'm guessing there's a simple solution but really can't figure it out.

我在 SO 上搜索了很多基本相同的问题,但似乎没有帮助。自从我接触 php 以来已经有一段时间了,所以我猜有一个简单的解决方案,但真的想不通。

config.php: (included into admin.php)

config.php:(包含在 admin.php 中)

$mysqli = new mysqli($mHost, $mUser, $mPass, $db);

admin.php:

管理.php:

$sqlQuery = "INSERT INTO `category` (`id`, `name`) VALUES ('', '$_POST[name]')";
$result = $mysqli->query($sqlQuery);

var_dump($result) returns:

var_dump($result) 返回:

NULL

空值

and gives error:

并给出错误:

Fatal error: Call to a member function query() on a non-object in

致命错误:在非对象上调用成员函数 query()

回答by Andy Lester

You are not checking the result of the call to new mysqli. If that fails, then $mysqliwill be null and not a valid object you can query against.

您没有检查调用的结果new mysqli。如果失败,$mysqli则将为 null 并且不是您可以查询的有效对象。

Also, by building SQL statements with outside variables, you are leaving yourself open to SQL injection attacks.Also, any input data with single quotes in it, like a name of "O'Malley", will blow up your SQL query. Please learn about using parametrized queries, preferably with the PDO module, to protect your web app. My site http://bobby-tables.com/phphas examples to get you started, and this questionhas many examples in detail.

此外,通过使用外部变量构建 SQL 语句,您将面临 SQL 注入攻击。此外,任何带有单引号的输入数据,例如“O'Malley”的名称,都会破坏您的 SQL 查询。请了解如何使用参数化查询(最好使用 PDO 模块)来保护您的 Web 应用程序。我的网站http://bobby-tables.com/php有一些例子可以帮助你入门,这个问题有很多详细的例子。

回答by mpyw

At the setout, you should call

在设置时,你应该打电话

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

This enables you don't have to check any return values, just put try { ... } catch { ... }blocks.

这使您不必检查任何返回值,只需放置try { ... } catch { ... }块即可。

try {

    if (
        !isset($_POST['name'])     ||
        !is_string($_POST['name']) ||
        $_POST['name'] === ''
    ) {
        throw new UnexpectedValueException('$_POST[\'name\'] is empty');
    }

    $mysqli = new mysqli($mHost, $mUser, $mPass, $db);
    $stmt = $mysqli->prepare("INSERT INTO `category` (`name`) VALUES (?)");
    $stmt->bind_param('s', $_POST['name']);
    $stmt->execute();

    echo 'Success';

} catch (Exception $e) {

    echo $e->getMessage();

}