Fatal error: Call to undefined function mysqli() i

2019-09-08 15:37发布

问题:

I am instentiating $db object this way in my database class

class db{
private $connection;

public function __construct(){
    $this->connect();
    }
public function connect(){
    $this->connection=mysqli_connect('localhost','root','','new5');
    }
   }
        $db=new db;

I am using this $db object in another class(profile class) as link identifier as

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

Please help me ,how can i get rid of this error.Actually I am recently shifted from mysql to mysqli.

回答1:

try

$db = mysqli_connect('localhost','root','XXX','XXX');


回答2:

$db = new mysqli('localhost','root','','test');
$sql = "select * from user";
$result = $db->query($sql);
var_dump($result->fetch_assoc());


回答3:

You are using procedural style of mysqli. So you must create query method in db class.

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
}

or you can use object oriented style with extends method;

class db extends mysqli{
  function __construct($host, $username, $password, $databaseName, $port=3306){
    mysqli::__construct($host, $username, $password, $databaseName, $port);
  }
}


回答4:

add a function

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

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


标签: php mysqli