duanchuanqu593743 2013-07-02 20:41
浏览 19
已采纳

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

This question already has an answer here:

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

</div>
  • 写回答

2条回答 默认 最新

  • dopnpoh056622 2013-07-02 20:46
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?