dtmbc1606 2014-06-25 10:31
浏览 48
已采纳

使用mysqli fetch assoc()获取mysqli结果时出错

This is my class for connecting to a database and it has a query method for looping through the results but it gives me this error:

Fatal error: Call to undefined method mysqli::fetch_assoc() in C:\Apache24\htdocs\classes\DB.php on line 30

I know that the problem is in my query() method and I have tried using non static properties but the error continues.

<?php

    class DB {
        private static $db_name = "data_db";
        private static $db_user = "root";
        private static $db_pass = "root";
        private static $db_host = "localhost";

        private static $row;
        private static $instance = null;

        public static function get_instance() {
            if(!isset(self::$instance))
                self::$instance = new self;

            return self::$instance;
        }

        //returns mysqli object.
        private function __construct() {
            $this->mysqli = new mysqli(self::$db_host, self::$db_user, self::$db_pass, self::$db_name);
        }

        public function __destruct() {
            $this->mysqli->close();
        }

        public function query($query) {
        if ($result = $this->mysqli->query($query)) {
            if($result->num_rows > 1) {
                $rows = array();            
                while ($item = $result->fetch_assoc()) {
                    $rows[] = $item;
                }
            } else {
                $rows = $result->fetch_assoc();
            }

                return $rows;
        }
    }

        /**
         * Private clone method to prevent cloning of the instance of the
         * *Singleton* instance.
         *
         * @return void
         */
        private function __clone() {}

        /**
         * Private unserialize method to prevent unserializing of the *Singleton*
         * instance.
         *
         * @return void
         */
        private function __wakeup() {}

    }
?>
  • 写回答

1条回答 默认 最新

  • dougan7523 2014-06-25 10:41
    关注

    MySQLi object doesn't have method fetch_assoc. You must use query result. Example:

    public function query($query) {
        $result = $this->mysqli->query($query);
    
        $rows = array();
        while ($item = $result->fetch_assoc()) {
            $rows[] = $item;
        }
    
        return $items;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog