I made this simple database function and a simple user class, but i can't implement the database connection inside the class.
dbconfig.php
<?php
session_start();
$db_user="root";
$db_pass="";
try {
$con = new PDO('mysql:host=localhost;dbname=hrm', $db_user, $db_pass);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
This is the class:
<?php
class user
{
private $db;
function __construct($con){
include_once '..\dbconfig.php';
$this->db=$con;
}
function listargeral($departamento){
try{
$stmt=$this->db->prepare("SELECT * from users where departamento=:departamento");
$stmt->execute(array(':departamento'=>$departamento));
while($userRow=$stmt->fetch(PDO::FETCH_ASSOC)){
echo ' <li data-jstree=\'{ "icon" : "fa fa-user" }\'>';
echo $userRow['nome']." - ".$userRow['acesso'];
echo '</li>';
}
} Catch(PDOException $e){
echo $e->getMessage();}
}
function logado(){
if(isset($_SESSION['sessao'])){
return true;
}
}
function entrar($username, $password){
try{
$stmt=$this->db->prepare("SELECT * from users where
user_name=:username LIMIT 1");
$stmt->execute(array(':username'=>$username));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowcount()>0){
$_SESSION['sessao']=$userRow['userid'];
return true;
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
There is any alternative? Thank you guys, i'm still learning.
UPDATE, header page for example:
<!doctype html>
<?php
require_once 'dbconfig.php';
include_once 'Class/class.user.php';
$user= new user($con);
// VERIFICAR SE ESTÁ LOGADO
if($user -> logado()==""){
$user->redirect('login.php');
}