1

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;
  }
}

1 Answer 1

2

$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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.