Clase 1
Código PHP:
class database {
private $host;
private $user;
private $password;
private $database;
private static $resultsql;
public static $instance;
public static $connectlink;
private function __construct() { }
public static function getInstance() {
if (!isset(self::$instance)) {
$db = __CLASS__;
self::$instance = new $db;
}
return self::$instance;
}
public function connect($host,$user,$password,$database){
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->database = $database;
self::$connectlink = mysql_connect($this->host,$this->user,$this->password);
if(!self::$connectlink) {
throw new Exception('A db connection is needed');
}
else {
mysql_select_db($this->database);
}
}
public static function sql($q) {
self::$resultsql = mysql_query($q);
return self::$resultsql;
}
public function disconnect() {
@mysql_close($this->connectlink);
}
public function __clone() {
throw new Exception('Clone are not allowed');
}
}
Código PHP:
class user {
private $user;
private $password;
private $result;
private $email;
private $iduser;
public function __construct($user,$password,$email="") {
if (!isset(database::$connectlink)) {
throw new Exception('A db connection is needed for instance this class');
} else {
$this->user = $user;
$this->password = $password;
$this->email = $email;
}
}
public function validateuser() {
$validate = database::sql("select * from USER where
USERNAME = '" . mysql_real_escape_string($this->user) . "'
AND PASSWORD = '" . mysql_real_escape_string(MD5($this->password)) ."'");
if (mysql_num_rows($validate) > 0)
{
mysql_free_result($validate);
return true;
}else {
mysql_free_result($validate);
return false;
}
}
public function checking(){
$validate_user = database::sql("select * from USER where
USERNAME = '" . mysql_real_escape_string($this->user) . "'
OR EMAIL = '" . mysql_real_escape_string($this->email) ."'");
if (mysql_num_rows($validate_user) > 0)
{
mysql_free_result($validate_user);
return true;
}else {
mysql_free_result($validate_user);
return false;
}
}
public function createuser() {
if($this->checking()) {
throw new Exception('The user exist or email already exist!');
} else {
database::sql("INSERT INTO USER ( USERNAME,PASSWORD, EMAIL)
VALUES ( '" . mysql_real_escape_string($this->user) . "' , '" . mysql_real_escape_string(MD5($this->password)) ."' , '" . mysql_real_escape_string($this->email) ."') ");
}
}
public function get_iduser() {
$this->result = database::sql("SELECT ID_USER from user where
USERNAME = '" . mysql_real_escape_string($this->user) . "'
and PASSWORD = '" . mysql_real_escape_string(MD5($this->password)) ."'");
while($row = mysql_fetch_array($this->result)) {
$this->iduser = $row['ID_USER'];
}
return $this->iduser;
}
}