PHP and MYSQLI Error, Call to a member function qu

2020-03-08 06:35发布

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

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

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

标签: php mysqli
2条回答
太酷不给撩
2楼-- · 2020-03-08 07:01

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.

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");

Only then you may call the methods of the mysqli class like $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

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.

查看更多
男人必须洒脱
3楼-- · 2020-03-08 07:15
 $link = mysqli_connect($hostname, $dbusername, $dbpassword, $dbname); 
 /////

 $result = $mysqli->query($sql);
           ///////
查看更多
登录 后发表回答