I'm not new to the PHP scene, I'm just not up to par with the language standards. I've recently stumbled upon a new style called OOP.
Anyways I have a few issues with my current script. I plan on expanding it but started with a "simple" script. My issues:
1. I'm unable to use $this->username in functions like "check_password" ideally I'd like to have it: function check_password() and it'd do $this->username, $this->password. The username/password would be set in the code (like below) but when attempted it just displays null. I've read online that I have to use magic functions as in __get or __set. I also want this to be as dynamic as possible so setVar($var) { $this->username = 'username'; } would not be feasible either.
2. In the function info() I want it to return whatever the request variable is .. right now it's only returning username. I'd assume it'd be something like $row->[$request]
Any help / links to any resources would be highly appreciated. Feel free to suggest alternatives to this current code as I'm still not sure this is the best way to go about things.
<?
$mysqli = new mysqli("localhost", "username", "password", "dbname");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
function query($q){
global $mysqli;
if(!$mysqli->query($q)){
die($mysqli->error);
}
return $mysqli->query($q);
}
class Database {
public static function close(){
global $mysqli;
$mysqli->close;
}
}
class Auth {
public $username;
public $password;
public $session_id;
public function check_password($username, $password) {
$result = query("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$password'");
if($result->num_rows > 0){
return true;
}
return false;
}
private function check_session($username, $session_id) {
$result = query("SELECT * FROM `users` WHERE `username`='$username' AND `session_id`='$session_id'");
if($result->num_rows > 0){
return true;
}
return false;
}
public function logged_in($username, $session_id) {
return $this->check_session($username, $session_id);
}
public function info($request, $username) {
$result = query("SELECT $request FROM `users` WHERE `username`='$username'");
if ($result->num_rows > 0){
$row = $result->fetch_object();
return $row->username;
}
return 'not found';
$result->close;
}
}
class User extends Auth {
public function get($result, $username) {
if($this->logged_in($username, $session_id)){
return $this->info($result, $username);
}
return null;
}
}
$auth = new Auth();
$auth->username = 'username';
$auth->password = 'password';
$auth->session_id = '55';
$user = new User();
if($auth->check_password($auth->username, $auth->password)){
echo 'Welcome: '.$user->get('username', $auth->username, $auth->session_id);
}else{
echo 'Incorrect Password';
}
Database::close();
?>