PHP 和 MYSQLI 错误,调用非对象上的成员函数 query()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17435493/
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 12:53:00  来源:igfitidea点击:

PHP and MYSQLI Error, Call to a member function query() on a non-object

phpmysqli

提问by dkeeper09

I'm getting the Call to a member function query() on a non-object when I try to call my function.

当我尝试调用我的函数时,我正在调用非对象上的成员函数 query()。

My code looks like this:

我的代码如下所示:

function add_profile() {

    $hostname = "localhost";
    $dbusername = "username";
    $dbname = "dbname";
    $dbpassword = "password";
    $link = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname); 
    if (!$link) { 
    die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); 
    } 

    $sql = "INSERT INTO payment_profiles(id, client_id) VALUES ( '','$profile_id')"; 

    $result = $mysqli->query($sql);
    if (!result) 
    { 
    echo 'Error: ', $mysqli->error;
    }
}

add_profile();

It says my error is on the line: $result = $mysqli->query($sql);

它说我的错误就行了: $result = $mysqli->query($sql);

I'm assuming I'm not calling something properly. Thanks in advance for any help

我假设我没有正确调用某些东西。在此先感谢您的帮助

回答by Saturnix

In your code you're mixing both procedural and object-oriented code. Choose either one or the other. Here's how you would solve the problem the procedural way.

在您的代码中,您混合了面向过程和面向对象的代码。选择其中之一。以下是您如何以程序方式解决问题。

$result = mysqli_query($link, $sql, MYSQLI_USE_RESULT)


I'm getting the Call to a member function query() on a non-object when I try to call my function.

当我尝试调用我的函数时,我正在调用非对象上的成员函数 query()。

That's because the $mysqliobject is not declared anywhere (or is it)? Before you can use $mysqliyou should first create an instance of mysqliand assign it to your object.

那是因为$mysqli对象没有在任何地方声明(或者是)?在您可以使用之前,$mysqli您应该首先创建一个实例mysqli并将其分配给您的对象。

$mysqli = new mysqli("localhost", "my_user", "my_password", "database");

Only then you may call the methods of the mysqli class like $mysqli->query();

只有这样你才能调用 mysqli 类的方法,如 $mysqli->query();

The error you made depends probably on two misconceptions:

您犯的错误可能取决于两个误解:

1) you pasted half of your code from the procedural-style part of the mysqli manual and half from the oop part

1)你从mysqli手册的程序风格部分粘贴了一半的代码,从oop部分粘贴了一半

2) you assume $mysqliis a global object instantiated with $mysqli_connect();. It is not. You should invoke the constructor with the newkeyword if you'd like to use it as an object.

2)您假设$mysqli是一个使用$mysqli_connect();. 它不是。new如果您想将其用作对象,则应使用关键字调用构造函数。

回答by CBroe

 $link = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname); 
 /////

 $result = $mysqli->query($sql);
           ///////