Page 1 of 1

Outputting message in middle of page from class.

Posted: Fri May 22, 2009 7:18 am
by Shabalaka
Hi guys i have a small problem, Im wishing to print out a message halfway through the html page, The connection class and user class is working fine i mean its returning the messages to the index.php page but its just outputting them at the top of the page.

After working with procedural code for quite a while now i decided to try and take the plunge into OOP PHP ,I am really new to OOP PHP so please take it easy on me if this isnt valid OOP yet....

The index.php page. I have stripped the body,head tags for miminal post

Code: Select all

<?php 
include_once('includes/connectionclass.php'); 
$connect = new Connections(); 
$connect -> EstablishConnection(); 
 
include_once("includes/userclass.php"); 
if (isset($_POST['login'])){ 
$NewUser = new User(); 
$loginerror = $NewUser->authorise(); 
 
} 
?> 
  <form id="form1" name="form1" method="post" action=""> 
    <table width="100%" border="0" cellspacing="0" cellpadding="0"> 
      <tr> 
        <td colspan="2">&nbsp;</td> 
        <td width="73%">&nbsp;</td> 
      </tr> 
      <tr> 
        <td colspan="2" class="centredfonts">Username</td> 
        <td><input name="username" type="text" class="inputs" id="username" /></td> 
      </tr> 
      <tr> 
        <td colspan="2" class="centredfonts">Password</td> 
        <td><label> 
          <input type="password" name="password" id="password" class="inputs" /> 
        </label></td> 
      </tr> 
      <tr> 
        <td colspan="2">&nbsp;</td> 
        <td><label> 
          <input type="submit" name="login" id="login" value="Login" /> 
        </label></td> 
      </tr> 
      <tr> 
        <td colspan="2">&nbsp;</td> 
       <td>&nbsp;</td> 
      </tr> 
      <tr> 
        <td width="9%">&nbsp;</td> 
        <td colspan="2" class="loginerror"><?php echo $loginerror;?></td> 
        </tr> 
    </table> 
     
    </form>
As you can see im trying to print out the returned value from $NewUser->authorise method here
The function/method inside userclass.php

Code: Select all

    function authorise(){
    $this->username = $_POST['username'];
    $this->password = $_POST['password'];
    $sql = "SELECT `username`,`password` from `users` WHERE `username` = '".$this->username."'";
    $query = mysql_query($sql);
    $result = mysql_num_rows($query);
    if ($result == 0){
        print "You dont seem to be registered.";
    }else{
        $UserArray = mysql_fetch_array($query);
        //check password
        if ($UserArray['password'] != $this->password){
            $this->loginerror = "Incorrect Username/Password";
            echo $this->loginerror;
        }else{
            $this->loginerror =  "Login Correct";
            echo $this->loginerror;
        }
    }
Also how would i go about conditioning the returned value from the method in the index.php page?
like this ?

Code: Select all

 
<?php 
if ($loginerror != ""){
echo "The value returned is different to nothing";
}
 
Sorry for the long post and thank you to all who take the time out to read it and reply :)
Regards Shab ;)

Re: Outputting message in middle of page from class.

Posted: Fri May 22, 2009 12:19 pm
by Griven
Your issue is with your function, particularly in this code block:

Code: Select all

 
if ($UserArray['password'] != $this->password){
             $this->loginerror = "Incorrect Username/Password";
             echo $this->loginerror;
         }else{
             $this->loginerror =  "Login Correct";
             echo $this->loginerror;
         }
 
The reason your message is coming out at the top, is you're telling your function to echo the string right then and there. What you should be doing is using the return command, so that whatever value is returned (your string in this case) is assigned to the variable that called this particular function.

More info: http://www.php.net/return

Also, I highly recommend sanitizing your user inputs. You've left yourself open to SQL injection with those unscrubbed POST variables.

Re: Outputting message in middle of page from class.

Posted: Fri May 22, 2009 12:49 pm
by Shabalaka
Thanks for the reply i made some changes to the code and now it looks like this :)

Code: Select all

// A user class....
class User {    
 
///Array for storing the retrieved array from UserQuery
    public $UserDetails = array();
 
 
//Every user will have these properties.
    public $username;
    public $password;
    public $fname;
    public $lname;
    public $email;
    public $loginerror;
             public $loginusername;
    public $loginpassword;
//Set the values to the above variables.
    function SetUser($_POST){
        $this->username = mysql_real_escape_string($_POST['username']);
        $this->password = mysql_real_escape_string(md5($_POST['password']));
        $this->fname = mysql_real_escape_string(ucfirst($_POST['fname']));
        $this->lname = mysql_real_escape_string(ucfirst($_POST['lname']));
        $this->email = mysql_real_escape_string($_POST['email']);
                          //Run field check 
        $this->FieldCheck();
            }
                          // This is the variables for when a user tries to log in .
        function SetUserLogin(){
        $this->loginusername = mysql_real_escape_string($_POST['username']);
        $this->loginpassword = mysql_real_escape_string(md5($_POST['password']));
        $this->Authorise();
        
    }       
            
        ///Base User Query 
        function UserQuery(){
            
        $sql="SELECT * FROM `users` WHERE `username` = '".$this->username."'";
        $query = mysql_query($sql);
        $result = mysql_fetch_array($query);
        $this->UserDetails = $result;
    
        }
 
    
    
function Authorise(){
    $this->UserQuery();
    if ($this->UserDetails['username'] == ""){
        $this->loginerror = "You dont seem to be registered.";
    }
    if (($this->loginusername == $this->UserDetails['username']) && ($this->loginpassword == $this->UserDetails['password'])){
        $this->loginerror = "Found you ";
    }
    $this->ErrorCheck();
    
 
}//END AUTHORISE        
    
        
        function FieldCheck(){
            if (($this->username == "") ||($this->password == "") || ($this->fname == "") || ($this->lname == "")){
                
                $this->loginerror .= "<li>Please fill out all fields.</li>";
                
            }
            $this->CheckEmail();
        }
 
 
        function CheckEmail(){
        $emailcheck = count_chars($this->email);
    
        $acount=$emailcheck[ord("@")];  
 
        if ($acount == 0){
            $this->loginerror .= "<li>Invalid email address</li>";
            
        }   
        $this->DuplicateUser();
        //$this->ErrorCheck();
    }
    
    
    
    function DuplicateUser(){
        
        $this->UserQuery();
        if ($this->UserDetails['username'] != ""){
            
            
            if($this->username == $this->UserDetails['username']){
                $this->loginerror .= "<li>Username taken</li>";
                
 
            }
        }
            $this->ErrorCheck();
            
            
        }
    
    function ForgottenPassword(){
        
    $this->UserQuery();
    if (($this->email == $this->UserDetails['email']) 
    && ($this->username == $this->UserDetails['username'])
    && ($this->fname == $this->UserDetails['fname'])){
    $this->loginerror .= "You have already registered<br>
                        <a href = 'login.php'>Forgotten Your Password?</a>";    
                        print_r($this->UserDetails);
        
        
    }
        $this->ErrorCheck();
        
    }
    
    
    function ErrorCheck(){
            if ($this->loginerror == ""){
                    $this->loginerror = "No errors on your application";
                    $this->InsertUser();
            }else{
                    
                    return $this->loginerror;
            }
            
            
        }
 
    
    
 
        function InsertUser(){
        ///Insert the user into the database.
            $sql = "INSERT INTO `users` (`username`,`password`,`fname`,`lname`,`email`) VALUES ('".$this->username."','".$this->password."','".$this->fname."','".$this->lname."','".$this->email."')";
        //Temp query handler
            $runquery = mysql_query($sql);
            //QueryHandler($this->sql);
            if(!$runquery){
                return $this->loginerror =  "Unable to insert user".$sql;
            }else{
                return $this->loginerror = "Registered!<br>
                <a href = 'index.php'>Please take me to the login page.</a>";
                
            }
    }
    
 
   
I made the changes for checking user inputs with mysql_real_escape_string function ( Was recommended by a friend ) , One thing im puzzling over now is this OOP because it feels like its more Procedural coding with a few bits of reused code ( UserQuery for example ) lol

Thanks for your reply :)

Any helpful suggestions regarding what type of layout i should have for a OOP based login and register system would be appreciated :)

My thoughts :
1 User class
1 connection handling class
1 User Login Class

I say UserLogin class because when i try to pass $_POST['username'] and $_POST['password'] to $this->username and $this->password i get Undefined Index errors because i havent assigned fname,lname and email any values , Anyway around this please?

Regards Shab.

Re: Outputting message in middle of page from class.

Posted: Sat May 23, 2009 11:49 am
by Griven
Yes, I would definitely use separate classes for user creation and user login, as these are different operations. One reads, the other writes.

Re: Outputting message in middle of page from class.

Posted: Fri May 29, 2009 10:32 am
by Shabalaka
Thanks very much for the help :) , I will take your advice as it seems very logical as like you said one reads from DB and other writes to it :)

Regards Shab. ;)