PHP user class with login access

I've searched something about a login system in Google but the thing is that I'm trying to get there by myself, and not following a guide that tells me everything.

I have an index.php that has a menu.php included in the top, which has an include for a login_form.php, which calls login.php to make the login. In the login.php uses the class User to make the login. user.php has the require_once for the connection.php

I'm failing at something very easy to fix but can't quite see it as this is new to me. The problem is that an error happens:

Undefined variable: mysql in admin\include\lib\user.php on line 12

connection.php:

 require_once 'constants.php';
 $mysql = new mysqli($db['host'], $db['username'], $db['password'], $db['name']);

if ($mysql->connect_error){
    die('Connection error (' . $mysql->connect_errno.')'. $mysql->connect_error);
}

user.php -> Line 12:

$this->password=$mysql->real_escape_string($this->password);

As a side note index.php as a require_once for the connection.php, constants.php (which has the $db array with the host, user, etc..), and the class.php. I'm really trying to get in th OOP concept so I would really appreciate your help!

Thanks in advance guys!

EDIT: I believe that it will be a bit hard to give you the file structure but I can assure you that I'm requiring things right. To prove it I did the var_dump($mysql). If I call it in the user.php but outside the class User, it shows content. However if I call it inside the class User, it gives me the undefined error.

Answers


You have a variable scope problem. $mysql is out of scope in the User class. I suggest passing the variable to the class in the constructor and store it as a property:

class User
{
    protected $mysql;   

    public function __construct($mysql)
    {
        $this->mysql = $mysql;
    }

    public function something()
    {
        $this->password = $this->mysql->real_escape_string($this->password);
    }
}

Example usage passing the connection:

require_once 'connection.php'; // creates $mysql
$user = new User($mysql);

Throughout the class you can now use $this->mysql to access the connection.


Need Your Help


About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.