从mysqli

时间:2016-01-27 16:57:34

标签: php mysqli

我一直在得到这个问题这个消息,我似乎无法弄清楚它的原因,“mysqli_query()期望参数1是mysqli” 这是我的代码(我有一个名为database的对象,可用于db连接和其他db函数);

 <?php 
      $sql="SELECT marque,cpu FROM pc";

      if ($result=mysqli_query($database->connection,$sql))
      {
          // Fetch one and one row
           while ($row=mysqli_fetch_row($result))
            { printf ("%s %s\n",$row[0],$row[1]);
            }
            // Free result set
            mysqli_free_result($result);
               }?>

以下是来自co.php的部分,负责数据库连接

enter code here
       class MySQLDatabase {
       public $connection;
       public function open_conection(){
       $connection=mysqli_connect('localhost', 'root', '', 'alpha');
        if (!$connection){
         die ("can't connect:".mysqli_error());
    }else {

    $select_db=mysqli_select_db($connection,'alpha');
    if(!$select_db) {
        die ('no database:' .mysqli_error());

} 
}
}
}

1 个答案:

答案 0 :(得分:0)

像这样改变你的课程:

class MySQLDatabase{

    private $connection;

    public function __construct(){
        $this->connection = mysqli_connect('localhost', 'root', '', 'alpha');
        if (!$connection){die ("can't connect:".mysqli_error())};
    }

    public function  get_connection(){
        return $this->connection;
    }
}

像这样使用:

<?php 

include 'MySQLDatabase.php';

$db = new MySQLDatabase();
$conn = $db->get_connection();

$sql="SELECT marque,cpu FROM pc";
if ($result=mysqli_query($conn,$sql)){
    // Fetch one and one row
    while ($row=mysqli_fetch_row($result))
    { 
        printf ("%s %s\n",$row[0],$row[1]);
    }
    // Free result set
    mysqli_free_result($result);
}else{
    echo 'query failed';
}
?>