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

报告相同问题?

悬赏问题

  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教