我正在尝试创建一个简单的使用单例类连接到mysql数据库并进行查询,代码工作正常,我没有遇到任何问题,但因为我是OOP的新手,我想知道这是否是不好的做法.
这是班级
class Database {
private $databaseName = 'dbname';
private $host = 'localhost';
private $user = 'user';
private $password = 'pass';
private static $instance; //store the single instance of the database
private function __construct(){
//This will load only once regardless of how many times the class is called
$connection = MysqL_connect($this->host,$this->user,$this->password) or die (MysqL_error());
$db = MysqL_select_db($this->databaseName,$connection) or die(MysqL_error());
echo 'DB initiated
sql = MysqL_query($query) or die(MysqL_error());
return $sql;
}
public function numrows($query) {
//count number of rows
$sql = $this->query($query);
return MysqL_num_rows($sql);
}
}
//Intantiate the class
$database = Database::getInstance();
当我想使用我会做的课时:
$query = "SELECT * FROM registrations";
echo $database->numrows($query);
$sql = $database->query($query);