在字符串OOP PHP

时间:2015-04-29 14:25:03

标签: php oop

我是OOP PHP的新手,所以我试着通过做一些基本的事情来学习,我得到的错误是在标题中查询只是一直返回那个错误。

<?php 

//CONNECTION STARTS HERE
class connection{

	private $host = 'localhost';
	private $username = 'root';
	private $password = '';
	private $database = 'test';
	public $conn;

	public function __construct(){

		return $this->conn = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die("MySQL Error");

	}

}

//USERS STARTS HERE
class users{

	public $db;

	public function __construct($db){

		$this->db = $db;

	}

	public function getAllUsernames($db){

		$query = "SELECT * FROM users";

        //ERROR IS ON THIS LINE
		$all_users = $this->db->query("$query");

		while ($row = $all_users->fetch_assoc()) {
			return $row['username'];
		}

	}
}

我不知道我哪里出错我可以帮助我更好地理解我做错了什么,我知道我必须清理很多以前的代码,但正如我所说的即时学习,这是另一个故事现在我只是想知道这个错误意味着什么以及它是什么......?

2 个答案:

答案 0 :(得分:1)

你实际上并不遥远。我稍微修改了你的代码并实例化你的类:

<?php 

//CONNECTION STARTS HERE
class connection {

    private $host = 'localhost';
    private $username = 'root';
    private $password = '';
    private $database = 'test';
    private $conn;

    public function __construct(){

        $this->conn = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die("MySQL Error");

    }

    public function getConn(){
        return $this->conn;
    }

}

//USERS STARTS HERE
class users {

    private $db;

    public function __construct($db){

        $this->db = $db;

    }

    public function getAllUsernames(){

        $query = "SELECT * FROM users";

        //ERROR IS ON THIS LINE
        $all_users = $this->db->query("$query");
        return $all_users;    
    }
}

$connection = new connection();
$users = new users($connection->getConn());

$allUsers = $users->getAllUsernames();
while ($row = $allUsers->fetch_assoc()) {
        echo $row['username'];
}

答案 1 :(得分:0)

看起来像语法错误,尝试这样的事情:

$sql = "SELECT * FROM users";
$query = $this->db->prepare($sql);
$query->execute();
return $query->fetchAll();