0

我在我的数据库类中以这种方式实例化 $db 对象

class MysqlDB {

    protected $_mysql;
    protected $_where = array();
    protected $_query;
    protected $_paramTypeList;
    protected $_crudType = null;

    public function __construct($host, $username, $password, $db) {
        $this->_mysql = new mysqli($host, $username, $password, $db) or die('There was a problem connecting to the database');
    }


    public function query($query)
    {
        $this->_query = filter_var($query, FILTER_SANITIZE_STRING);

        $stmt = $this->_prepareQuery();
        $stmt->execute();
        $results = $this->_dynamicBindResults($stmt);
        return $results;
    }
        protected function _prepareQuery()
    {
        echo $this->_query;
        if (!$stmt = $this->_mysql->prepare($this->_query)) {
            trigger_error("Problem preparing query", E_USER_ERROR);
        }
        return $stmt;
    }

}

我在另一个类(配置文件类)中使用这个 $db 对象作为链接标识符

$db = new MysqlDb('localhost','root','','xxx');

$query=mysqli_query($db,"SELECT id, parent_id, name FROM categories_general");

我怎样才能摆脱这个错误?实际上,我最近从 MySQL 转到了 mysqli。

4

4 回答 4

6

尝试

$db = mysqli_connect('localhost','root','XXX','XXX');
于 2012-11-01T03:49:08.673 回答
2
$db = new mysqli('localhost','root','','test');
$sql = "select * from user";
$result = $db->query($sql);
var_dump($result->fetch_assoc());
于 2012-11-01T03:48:18.707 回答
2

您正在使用 mysqli 的程序样式。所以你必须在 db 类中创建查询方法。

class db{
  private $connection;

  public function __construct(){
    $this->connect();
  }
  public function connect(){
    $this->connection=mysqli_connect('localhost','root','','new5');
  }
  //add these methods
  public function query($query_string){
    return mysqli_query($this->connection, $query_string);
  }
  public function fetch_row($mysqli_result){
    return mysqli_fetch_row($this->connection, $mysqli_result);
  }
  //and other functions you need
}

或者您可以使用带扩展方法的面向对象样式;

class db extends mysqli{
  function __construct($host, $username, $password, $databaseName, $port=3306){
    mysqli::__construct($host, $username, $password, $databaseName, $port);
  }
}
于 2014-07-20T21:04:46.293 回答
0

添加一个功能

public function getDB()
{
    return $this->_mysql;
}

 $query=mysqli_query($db->getDB(),"SELECT id, parent_id, name FROM categories_general");
于 2012-11-01T05:10:40.253 回答