0

I always made a procedural php but I want to change my way of working (t is never too late to change bad habits)

I have 3 files : pdo.php

<?php
try 
    {
        $engine = 'mysql';
        $host ='localhost';
        $port = '';
        $database = 'local';
        $user = 'root';
        $password = '';
        $dns = $engine.':port='.$port.';dbname='.$database.";host=".$host;

        $bdd = new PDO($dns, $user, $password);
    }

catch (Exeption $erreur)
    {
        die ('Erreur : '.$erreur->getMessage());
    }
?>

User.php

<?php

include 'pdo.php';

class User {

    private $bdd;

    private $id;
    private $firstname;
    private $lastname;
    private $email;


    public function getId(){
        return $this->id;
    }

    public function setId($id){
        $this->id = $id;
    }


    //ALL GETTER AND SETTER


    public function getUserIdByEmail($email) {

        $request = $this->bdd->prepare("select id from users where email = :email");
        $request->execute(array(
            ':email' => $email,
        ));
        return $request->fetchColumn();

    }
}

And index.php

<?php session_start (); 
include 'pdo.php';
require 'User.php';
?>

<?php if (isset($_SESSION["email"]) && isset($_SESSION["password"])) { 

    $userEmail = $_SESSION["email"];
    $userId = new User();
    $id = $userId->getUserIdByEmail($userEmail);
    echo $id;

//Rest of code

I don't understand how I can access to my objet in pdo.php I have try various possibility (like include pdo.php in class User) but it doesn't work ..

Can you explain how I can do ? Thank you

Rocstar
  • 1,427
  • 3
  • 23
  • 41
  • You should pass the global `$bdd` variable to the constructor of your user class to set the class' `$bdd` property. Look for *dependency injection* for more information. – jeroen Feb 15 '17 at 14:41
  • just add a constructor to your userclass and set bdd through a parameter – Your Common Sense Feb 15 '17 at 15:12
  • Like this ? -- **public function __construct($bdd) { $this->setDb($bdd); }** -- Thank you for your answer – Rocstar Feb 15 '17 at 15:38

0 Answers0