如何在PHP类中使用mysqli_query?

时间:2015-01-27 10:06:20

标签: php mysql database mysqli

如何在$connect类中使用User变量而不发送$connect作为参数或在User类中定义global $connect

我想只创建一个连接

$connect = mysqli_connect('localhost', 'root', '1234', 'mydatabase');

错误

警告: mysqli_query()要求参数1为mysqli,在第9行 D:\ xampp \ htdocs \ mateocode \ index.php 中给出null

示例代码

<?php
    class User {    
        public $id;
        public $username;
        function __construct($user_id)
        {   
        $sql = "select id, username from user where id = '$user_id' limit 1";

        $result = mysqli_query($connect, $sql);    
        if(!$result) return false;

        if(mysqli_num_rows($result)>0){
            $data = mysqli_fetch_assoc($result);
            $this->id = $data['id'];
            $this->username = $data['username'];
        }else{ 
            return false; 
        }   
    }
}

$connect = mysqli_connect('localhost', 'root', '1234', 'mydatabase');

if($objUser = new User(1))
    echo $objUser->username;
else 
    echo 'There was an error or user not found!'; 

1 个答案:

答案 0 :(得分:0)

尝试 -

<?php
    class User {    
        public $id;
        public $username;
        function __construct($user_id, $connect)
        {   
        $sql = "select id, username from user where id = '$user_id' limit 1";

        $result = mysqli_query($connect, $sql);    
        if(!$result) return false;

        if(mysqli_num_rows($result)>0){
            $data = mysqli_fetch_assoc($result);
            $this->id = $data['id'];
            $this->username = $data['username'];
        }else{ 
            return false; 
        }   
    }
}

$connect = mysqli_connect('localhost', 'root', '1234', 'mydatabase');

if($objUser = new User(1, $connect))
    echo $objUser->username;
else 
    echo 'There was an error or user not found!';