Miljan Ilic
Miljan Ilic

Reputation: 335

PHP Class - Use return in another function

I have one PHP Class with 2 functions DB_Connect() and LogIn(). To use LogIn() I first need to run DB_Connect and get returned value of $CONN. I do this with $this->DB_Connect(); but when I run code I'm get:

Notice: Undefined variable: CONN in C:\XAMPP\htdocs\core\Admin.class.php on line 39

Fatal error: Call to a member function prepare() on null in C:\XAMPP\htdocs\core\Admin.class.php on line 39

protected function DB_Connect()
{
  $ROOT = dirname(__DIR__);
  include $ROOT."../core/sql.php";

  try {
    $CONN = new PDO("mysql:host=$ServerName; dbname=$DataBase", $Username, $Password);
    $CONN->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $CONN->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  } catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
  }

  return $CONN;
}

public function LogIn()
{
  if($_SERVER["REQUEST_METHOD"] === "POST") {
    $Username = $_POST["Username"];
    $Password = $_POST["Password"];

    $this->DB_Connect();

    try {
       $SQL = "SELECT Password FROM Admins WHERE Username = :Username";
       $SQL = $CONN->prepare($SQL);
       $SQL->execute(array('Username' => $Username));
       $CountRows = $SQL->rowCount();
       $Result = $SQL->fetch(PDO::FETCH_ASSOC);
       $PasswordCheck = $Result["Password"];
       if($CountRows === "1" && password_verify($Password, $PasswordCheck)) {
         $_SESSION["LoginUser"] = $Username;
         $CONN = null;
         header("location: home.php");
         exit();
       } else {
         $Status = '<div class="alert alert-danger" role="alert">You have entered wrong data!</div>';
       }
    } catch(PDOException $e) {
       echo "Connection failed: " . $e->getMessage();
    }
  }
  $CONN = null;
  if(isset($Status)) {
    return $Status;
  }
}

Upvotes: 1

Views: 137

Answers (1)

gen_Eric
gen_Eric

Reputation: 227310

$this->DB_Connect(); returns a value. It doesn't set a variable for you. You need to set a variable to its return value.

$CONN = $this->DB_Connect();

Upvotes: 2

Related Questions