Jump to content

OO PHP - passing variable from class to HTML


tim87

Recommended Posts

Hi,

 

I've just made the move to OO and have a problem printing an error message from a login script.

 

login.php contains my form and retrieves the username and password. Calls the authentication class and passes username and pass to the Login object.

 

login.php

$login = new authentication();

if(isset($_POST['login'])){
$username = $_POST[user];
$pass = $_POST[pass]; 
$login->Login($username, $pass);
	}

 

classes.php

public function LoginError($error){ 
   echo $error; 
   } 

   public function Login($username, $pass){ 
    
      $db = new Database; 
      $Query = "SELECT * from user where Username='$username' AND Password='$pass'"; 
      $db->query($Query);        
      $db->singleRecord();    
       
      if($db->numRows() > 1){ 
          
          $this->LoginError("Login error please contact Adminstraitor"); 
      } 
      elseif ($db->numRows() == 0){ 
          
         $this->LoginError("Username or Password incorrect, please try again"); 
      } 
      else{ 
       
         header( "Location: home.php" ); 
      } 
   }

 

What I am trying to achieve is to print the LoginError in a div in login.php

 

<div id="content"><?php $login->LoginError();?></div>

 

But instead of appearing on the page in the div it appears at the top of the page above my header (forcing my header down).

 

Can anyone explain/show me how to print the error message within my HTML?

 

Thanks in advance

 

Tim

I'd add a bit of value checking and clearer methods to your class, because right now you're asking LoginError to do a bit too much (both registering the error and displaying it):

 

<?php
class Authentication
{
   private $error;

   private function hasError()
   {
      if (!empty($this->error)) { return true; }
      else { return false; }
   }

   public function displayError()
   {
      if ($this->hasError()) { echo $this->error; }
   }
   
   public function Login($username, $pass)
   { 
      $db = new Database(); 
      $query = "SELECT * from user where Username='$username' AND Password='$pass'"; 
      $db->query($query);        
      $db->singleRecord();    
       
      if ($db->numRows() > 1)
      {   
         $this->error = "Login error: Please contact Adminstraitor"; 
      } 
      elseif ($db->numRows() == 0)
      {     
         $this->error = "Username or Password incorrect, please try again"; 
      } 
      else
      { 
         header( "Location: home.php" ); 
      }
   }
}
?>

<div id="content"><?php $login->displayError(); ?></div>

 

If that doesn't help, show more code.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.