PHP和MYSQLI错误,在非对象上调用成员函数query() [英] PHP and MYSQLI Error, Call to a member function query() on a non-object
问题描述
当我尝试调用函数时,我正在非对象上调用成员函数query().
I'm getting the Call to a member function query() on a non-object when I try to call my function.
我的代码如下:
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();
它说我的错误在网上:$result = $mysqli->query($sql);
It says my error is on the line: $result = $mysqli->query($sql);
我假设我打的电话不正确.预先感谢您的帮助
I'm assuming I'm not calling something properly. Thanks in advance for any help
推荐答案
在您的代码中,您将混合过程代码和面向对象的代码.选择一个或另一个.这是您如何以程序方式解决问题的方法.
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)
我在非对象上收到对成员函数query()的调用 我尝试调用我的函数.
I'm getting the Call to a member function query() on a non-object when I try to call my function.
那是因为在任何地方都没有声明$mysqli
对象吗?在使用$mysqli
之前,您应该首先创建mysqli
的实例并将其分配给您的对象.
That's because the $mysqli
object is not declared anywhere (or is it)? Before you can use $mysqli
you should first create an instance of mysqli
and assign it to your object.
$mysqli = new mysqli("localhost", "my_user", "my_password", "database");
只有这样,您才可以调用mysqli类的方法,例如$mysqli->query();
Only then you may call the methods of the mysqli class like $mysqli->query();
您犯的错误可能取决于两个误解:
The error you made depends probably on two misconceptions:
1)您从mysqli手册的过程样式部分粘贴了一半代码,而从oop部分粘贴了一半代码
1) you pasted half of your code from the procedural-style part of the mysqli manual and half from the oop part
2)您假定$mysqli
是用$mysqli_connect();
实例化的全局对象.它不是.如果想将其用作对象,则应使用new
关键字调用该构造函数.
2) you assume $mysqli
is a global object instantiated with $mysqli_connect();
. It is not. You should invoke the constructor with the new
keyword if you'd like to use it as an object.
这篇关于PHP和MYSQLI错误,在非对象上调用成员函数query()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!