php mysqli query expects parameter 1 be to string

2019-03-05 11:48发布

问题:

I was coding a User database which calls an static method of find_all which calls an query method which in turn returns all the value of a database but i am finding trouble in doing so each time when i try to call it it gives me these error as mysqli_query() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\photogallery\includes\database.php on line 20.What do i do? Here is the code snippet User.php

require_once("database.php");
class User{

public  static function find_all(){
    global $database;
    $sql= "select * from users";
    $result_set = $database->query($sql);


return $result_set; 
    }
    public  static function find_by_id($id=0){
        global $database;
        $result_set = $database->query("SELECT FROM users where id={$id}");
        $found = $database->fetch_array($result_set);
        return $found;  
    }
}

Database.php

 public function query($sql){
echo $sql;
$this->last_query = $sql;
echo $result = mysqli_query($sql,$this->connection);
 $this->confirm_query($result);
 return $result;


}

 public function confirm_query($result){
    if(!$result){
        die("Database query failed:".mysqli_error());
    }
 }

and the index.php where the code is called as follows :

   <?php
require_once("../includes/database.php");
require_once("../includes/user.php");

 $q = User::find_all();


?>

Each time the error comes as mysqli_query expects parameter 1 to be mysqli,string given in C:\xampp\htdocs\photogallery\includes\database.php on line 20.Help me out please??

回答1:

When using mysqli in a procedural style, the first argument to mysqli_query must be a connection object

From the official documentation:

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

So you need to change the order of the arguments, $this->connection goes first and $sql goes second:

$result = mysqli_query($this->connection, $sql);


回答2:

Just read docs:
mixed

mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )    

You must change your arguments to

mysqli_query($this->connection, $sql)