Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 3 123 LastLast
Results 1 to 15 of 41
  1. #1
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts

    Angry oop programming - help to understand and modify please

    Hi All,

    I have (what i think is) a complex website that i am currently creating, i have recently integrated a login script which i found online and it works very well.

    the only problem i am having is that i think it is written in OOP and not procedule programming that i am used to.

    I am trying to find and return the number of results of a db query

    so my login code is
    PHP Code:
    <div class="user-account-bar">
        
        <div class="user-account">
            <ul id="account-menu">  
                <li class="menu_right"><a href="#" class="drop">Welcome
                    <?php if($session->logged_in)
                    {
                        echo 
    "<b>$session->username</b>";
                    }
                    else
                    {
                        echo 
    "<b>Guest</b>";
                    }
    ?><br />
                    Your Account
                    </a> 
              
                    <div class="dropdown_2columns align_right"> 
                      
                    <div class="col_2">  
                    <?php if(!$session->logged_in)
                    {
    ?>
                        <a class="button orange full-width" href="signin.php">Sign In</a>
                        <div class="sign-up">Don't Have An Account? <a href='register.php'>Sign Up</a></div><?php
                    
    }
                    else
                    {
    ?>
                        <a class="button orange full-width" style="margin-bottom:5px;" href="userinfo.php?user=<?php echo $session->userid?>">My Account</a>
                        <a class="button orange full-width" style="margin-bottom:5px;" href="location.php?l=223">Whats on in my village?</a><?php
                    
    }
                    if(
    $session->isAdmin())
                    {
    ?>
                        <a class="button orange full-width" style="margin-bottom:5px;" href="admin/admin.php">Admin Center</a><?php
                    
    }?>
                    </div>  
                      
                    <div class="col_1">  
              
                        <ul class="greybox">  
                            <li><a href="#">Create Job</a></li>  
                            <li><a href="#">Add Accomodation</a></li>  
                            <li><a href="#">black</a></li>  
                        </ul>     
              
                    </div>  
                      
                    <div class="col_1">  
              
                        <ul class="greybox">  
                            <li><a href="#">List a Business</a></li>  
                            <li><a href="#">Create an Event</a></li>  
                            <li><a href="#">Promote your trade</a></li>  
                        </ul>     
              
                    </div>  
                    
                    <?php if($session->logged_in)
                    {
    ?>
                        <a class="button black full-width" href="process.php">Sign Out</a><?php
        
                    
    }?>
                    
                    </div>
        
                </li>
                
                <?php if($session->logged_in)
                {
    ?>         
                <li class="notification-container">
                    
                    <span class="notification-counter">
                    <?php $session->userNotifications;?>
                    </span>
                </li>
                <li class="notification-container">
                    
                    <span class="notification-counter">1</span>
                </li>
                <li class="notification-container">
                    
                    <span class="notification-counter">100</span>
                </li>
                <li class="notification-container">
                    
                    <span class="notification-counter">1</span>
                </li>
                <li class="notification-container">
                    
                    <span class="notification-counter">1</span>
                </li>
                <?php
                
    }
                else
                {
    ?>
                    <li class="notification-container">
                        
                    </li>
                    <li class="notification-container">
                        
                    </li>
                    <li class="notification-container">
                        
                    </li>
                    <li class="notification-container">
                        
                    </li>
                    <li class="notification-container">
                        
                    </li><?php
                
    }?>
            </ul>
        </div>
        
    </div>
    this is where i want to return the number of rows
    PHP Code:
    <span class="notification-counter"><?php $session->userNotifications;?></span>
    my login code is in a seperate php file called login.php and is included on each of my main pages

    but i dont know how to use the session page correctly to help me get the results i want?

    the login script has two main php files included with it
    session.php and database.php

    but im not sure how to use them correctly to get what i want

    i will post the session.php and database pages below in seperate posts to help make it easier to follow (hopefully )

  • #2
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    session.php file is
    PHP Code:
    <?php
    /**
     * Session.php
     * 
     * The Session class is meant to simplify the task of keeping
     * track of logged in users and also guests.
     *
     *  Please subscribe to our feeds at http://blog.geotitles.com for more such tutorials
     */
    include("database.php");
    include(
    "mailer.php");
    include(
    "form.php");

    class 
    Session
    {
       var 
    $username;     //Username given on sign-up
       
    var $userid;       //Random value generated on current login
       
    var $userlevel;    //The level to which the user pertains
       
    var $time;         //Time user was last active (page loaded)
       
    var $logged_in;    //True if user is logged in, false otherwise
       
    var $userinfo = array();  //The array holding all user info
       
    var $url;          //The page url current being viewed
       
    var $referrer;     //Last recorded site page viewed
       /**
        * Note: referrer should really only be considered the actual
        * page referrer in process.php, any other time it may be
        * inaccurate.
        */

       /* Class constructor */
       
    function Session(){
          
    $this->time time();
          
    $this->startSession();
       }

       
    /**
        * startSession - Performs all the actions necessary to 
        * initialize this session object. Tries to determine if the
        * the user has logged in already, and sets the variables 
        * accordingly. Also takes advantage of this page load to
        * update the active visitors tables.
        */
       
    function startSession(){
          global 
    $database;  //The database connection
          
    session_start();   //Tell PHP to start the session

          /* Determine if user is logged in */
          
    $this->logged_in $this->checkLogin();

          
    /**
           * Set guest value to users not logged in, and update
           * active guests table accordingly.
           */
          
    if(!$this->logged_in){
             
    $this->username $_SESSION['username'] = GUEST_NAME;
             
    $this->userlevel GUEST_LEVEL;
             
    $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
          }
          
    /* Update users last active timestamp */
          
    else{
             
    $database->addActiveUser($this->username$this->time);
          }
          
          
    /* Remove inactive visitors from database */
          
    $database->removeInactiveUsers();
          
    $database->removeInactiveGuests();
          
          
    /* Set referrer page */
          
    if(isset($_SESSION['url']))
          {
             
    $this->referrer $_SESSION['url'];
          }
          else{
             
    $this->referrer "/";
          }

          
    /* Set current url */
          
    $this->url $_SESSION['url'] = $_SERVER['PHP_SELF'];
       }

       
    /**
        * checkLogin - Checks if the user has already previously
        * logged in, and a session with the user has already been
        * established. Also checks to see if user has been remembered.
        * If so, the database is queried to make sure of the user's 
        * authenticity. Returns true if the user has logged in.
        */
       
    function checkLogin(){
          global 
    $database;  //The database connection
          /* Check if user has been remembered */
          
    if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
             
    $this->username $_SESSION['username'] = $_COOKIE['cookname'];
             
    $this->userid   $_SESSION['userid']   = $_COOKIE['cookid'];
          }

          
    /* Username and userid have been set and not guest */
          
    if(isset($_SESSION['username']) && isset($_SESSION['userid']) &&
             
    $_SESSION['username'] != GUEST_NAME){
             
    /* Confirm that username and userid are valid */
             
    if($database->confirmUserID($_SESSION['username'], $_SESSION['userid']) != 0){
                
    /* Variables are incorrect, user not logged in */
                
    unset($_SESSION['username']);
                unset(
    $_SESSION['userid']);
                return 
    false;
             }

             
    /* User is logged in, set class variables */
             
    $this->userinfo  $database->getUserInfo($_SESSION['username']);
             
    $this->username  $this->userinfo['username'];
             
    $this->userid    $this->userinfo['userid'];
             
    $this->userlevel $this->userinfo['userlevel'];
             
    $this->lastlogin $this->userinfo['lastlogin'];
             
    $this->townid $this->userinfo['placeID'];
             
             return 
    true;
          }
          
    /* User not logged in */
          
    else{
             return 
    false;
          }
       }

       
    /**
        * login - The user has submitted his username and password
        * through the login form, this function checks the authenticity
        * of that information in the database and creates the session.
        * Effectively logging in the user if all goes well.
        */
       
    function login($subuser$subpass$subremember){
          global 
    $database$form;  //The database and form object

          /* Username error checking */
          
    $field "user";  //Use field name for username
          
    if(!$subuser || strlen($subuser trim($subuser)) == 0){
             
    $form->setError($field"* Username not entered");
          }
          else{
             
    /* Check if valid email address */
             
    $regex "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
                     
    ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
                     
    ."\.([a-z]{2,}){1}$";
             if(!
    eregi($regex,$subuser)){
                
    $form->setError($field"* Email invalid");
             }
             
    $subuser stripslashes($subuser);
          }

          
    /* Password error checking */
          
    $field "pass";  //Use field name for password
          
    if(!$subpass){
             
    $form->setError($field"* Password not entered");
          }
          
          
    /* Return if form errors exist */
          
    if($form->num_errors 0){
             return 
    false;
          }

          
    /* Checks that username is in database and password is correct */
          
    $subuser stripslashes($subuser);
          
    $result $database->confirmUserPass($subusermd5($subpass));

          
    /* Check error codes */
          
    if($result == 1){
             
    $field "user";
             
    $form->setError($field"* Username not found");
          }
          else if(
    $result == 2){
             
    $field "pass";
             
    $form->setError($field"* Invalid password");
          }
          
          
    /* Return if form errors exist */
          
    if($form->num_errors 0){
             return 
    false;
          }

          
    /* Username and password correct, register session variables */
          
    $this->userinfo  $database->getUserInfo($subuser);
          
    $this->username  $_SESSION['username'] = $this->userinfo['username'];
          
    $this->userid    $_SESSION['userid']   = $this->generateRandID();
          
    $this->userlevel $this->userinfo['userlevel'];
          
          
    /* Insert userid into database and update active users table */
          
    $database->updateUserField($this->username"userid"$this->userid);
          
    $database->addActiveUser($this->username$this->time);
          
    $database->removeActiveGuest($_SERVER['REMOTE_ADDR']);

          
    /**
           * This is the cool part: the user has requested that we remember that
           * he's logged in, so we set two cookies. One to hold his username,
           * and one to hold his random value userid. It expires by the time
           * specified in constants.php. Now, next time he comes to our site, we will
           * log him in automatically, but only if he didn't log out before he left.
           */
          
    if($subremember){
             
    setcookie("cookname"$this->usernametime()+COOKIE_EXPIRECOOKIE_PATH);
             
    setcookie("cookid",   $this->userid,   time()+COOKIE_EXPIRECOOKIE_PATH);
          }

          
    /* Login completed successfully */
          
    return true;
       }

       
    /**
        * logout - Gets called when the user wants to be logged out of the
        * website. It deletes any cookies that were stored on the users
        * computer as a result of him wanting to be remembered, and also
        * unsets session variables and demotes his user level to guest.
        */
       
    function logout(){
          global 
    $database;  //The database connection
          /**
           * Delete cookies - the time must be in the past,
           * so just negate what you added when creating the
           * cookie.
           */
          
    if(isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])){
             
    setcookie("cookname"""time()-COOKIE_EXPIRECOOKIE_PATH);
             
    setcookie("cookid",   ""time()-COOKIE_EXPIRECOOKIE_PATH);
          }

          
    /* Unset PHP session variables */
          
    unset($_SESSION['username']);
          unset(
    $_SESSION['userid']);

          
    /* Reflect fact that user has logged out */
          
    $this->logged_in false;
          
          
    /**
           * Remove from active users table and add to
           * active guests tables.
           */
          
    $database->removeActiveUser($this->username);
          
    $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
          
          
    /* Update Last Login IN User table */
          
    $database->updateLastLogin($this->username$this->time);
          
          
    /* Set user level to guest */
          
    $this->username  GUEST_NAME;
          
    $this->userlevel GUEST_LEVEL;
       }

       
    /**
        * register - Gets called when the user has just submitted the
        * registration form. Determines if there were any errors with
        * the entry fields, if so, it records the errors and returns
        * 1. If no errors were found, it registers the new user and
        * returns 0. Returns 2 if registration failed.
        */
        
    function register($subemail$fname$lname$subpass$subpass2 )
           {
            global 
    $database$form$mailer;  //The database, form and mailer object
          
            /* Email error checking */
              
    $field "email";  //Use field name for email
              
    if(!$subemail || strlen($subemail trim($subemail)) == 0)
              {
                
    $form->setError($field"* Email not entered");
              }
              else
              {
                
    /* Check if valid email address */
                 
    $regex "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
                         
    ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
                         
    ."\.([a-z]{2,}){1}$";
                 if(!
    eregi($regex,$subemail))
                 {
                    
    $form->setError($field"* Email invalid");
                 }
                 
    $subemail stripslashes($subemail);
              }
          
              
    /* FName error checking */
              
    $field "fname";  //Use field name for username
              
    if(!$fname || strlen($fname trim($fname)) == 0)
              {
                 
    $form->setError($field"* First Name not entered");
              }
              else
              {
                 
    /* Spruce up username, check length */
                 
    $fname stripslashes($fname);
                 if(
    strlen($fname) < 2)
                 {
                    
    $form->setError($field"* Name must be greater than 1 characters");
                 }
                 
    /* Check if username is not alphanumeric */
                 
    else if(!eregi("^([0-9a-z])+$"$fname))
                 {
                    
    $form->setError($field"* First Name not alphanumeric");
                 }
            }
                
            
    /* Last Name error checking */
              
    $field "lname";  //Use field name for username
              
    if(!$lname || strlen($lname trim($lname)) == 0)
            {
                 
    $form->setError($field"* Last Name not entered");
              }
              else
            {
                 
    /* Spruce up username, check length */
                 
    $lname stripslashes($lname);
                 if(
    strlen($lname) < 2)
                {
                    
    $form->setError($field"* Last Name must be greater than 1 characters");
                 }
                 
    /* Check if username is not alphanumeric */
                 
    else if(!eregi("^([0-9a-z])+$"$lname))
                {
                    
    $form->setError($field"* Last Name not alphanumeric");
                 }
            }


          
    /* Password error checking */
          
    $field "pass";  //Use field name for password
          
    if(!$subpass){
             
    $form->setError($field"* Password not entered");
          }
          else{
             
    /* Spruce up password and check length*/
             
    $subpass stripslashes($subpass);
             if(
    strlen($subpass) < 4){
                
    $form->setError($field"* Password too short");
             }
             
    /* Check if password is not alphanumeric */
             
    else if(!eregi("^([0-9a-z])+$", ($subpass trim($subpass)))){
                
    $form->setError($field"* Password not alphanumeric");
             }
             
    /**
              * Note: I trimmed the password only after I checked the length
              * because if you fill the password field up with spaces
              * it looks like a lot more characters than 4, so it looks
              * kind of stupid to report "password too short".
              */
          
    }
          
          
    /* Password confirm error checking */
          
    $field "pass-confirm";  //Use field name for password
          
    if(!$subpass2)
          {
             
    $form->setError($field"* Confirmation Password not entered");
          }
          else
          {
             
    /* Spruce up password and check length*/
             
    $subpass2 stripslashes($subpass2);
             if(
    strlen($subpass2) < 4)
             {
                
    $form->setError($field"* Confirmation Password too short");
             }
             
    /* Check if password is not alphanumeric */
             
    else if(!eregi("^([0-9a-z])+$", ($subpass2 trim($subpass2))))
             {
                
    $form->setError($field"* Confirmation Password not alphanumeric");
             }
             
             else if(
    $subpass2 != $subpass)
             {
                
    $form->setError($field"* Passwords Dont Match!");     
             }
             
    /**
              * Note: I trimmed the password only after I checked the length
              * because if you fill the password field up with spaces
              * it looks like a lot more characters than 4, so it looks
              * kind of stupid to report "password too short".
              */
          
    }
          

          
    /* Errors exist, have user correct them */
          
    if($form->num_errors 0){
             return 
    1;  //Errors with form
          
    }
          
    /* No errors, add the new account to the */
          
    else{
             if(
    $database->addNewUser($subusermd5($subpass), $subemail$fname$lname)){
                if(
    EMAIL_WELCOME){
                   
    $mailer->sendWelcome($subuser,$subemail,$subpass);
                }
                return 
    0;  //New user added succesfully
             
    }else{
                return 
    2;  //Registration attempt failed
             
    }
          }
       }
       
       
    /**
        * editAccount - Attempts to edit the user's account information
        * including the password, which it first makes sure is correct
        * if entered, if so and the new password is in the right
        * format, the change is made. All other fields are changed
        * automatically.
        */
       
    function editAccount($subcurpass$subnewpass$subemail){
          global 
    $database$form;  //The database and form object
          /* New password entered */
          
    if($subnewpass){
             
    /* Current Password error checking */
             
    $field "curpass";  //Use field name for current password
             
    if(!$subcurpass){
                
    $form->setError($field"* Current Password not entered");
             }
             else{
                
    /* Check if password too short or is not alphanumeric */
                
    $subcurpass stripslashes($subcurpass);
                if(
    strlen($subcurpass) < ||
                   !
    eregi("^([0-9a-z])+$", ($subcurpass trim($subcurpass)))){
                   
    $form->setError($field"* Current Password incorrect");
                }
                
    /* Password entered is incorrect */
                
    if($database->confirmUserPass($this->username,md5($subcurpass)) != 0){
                   
    $form->setError($field"* Current Password incorrect");
                }
             }
             
             
    /* New Password error checking */
             
    $field "newpass";  //Use field name for new password
             /* Spruce up password and check length*/
             
    $subpass stripslashes($subnewpass);
             if(
    strlen($subnewpass) < 4){
                
    $form->setError($field"* New Password too short");
             }
             
    /* Check if password is not alphanumeric */
             
    else if(!eregi("^([0-9a-z])+$", ($subnewpass trim($subnewpass)))){
                
    $form->setError($field"* New Password not alphanumeric");
             }
          }
          
    /* Change password attempted */
          
    else if($subcurpass){
             
    /* New Password error reporting */
             
    $field "newpass";  //Use field name for new password
             
    $form->setError($field"* New Password not entered");
          }
          
          
    /* Email error checking */
          
    $field "email";  //Use field name for email
          
    if($subemail && strlen($subemail trim($subemail)) > 0){
             
    /* Check if valid email address */
             
    $regex "^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*"
                     
    ."@[a-z0-9-]+(\.[a-z0-9-]{1,})*"
                     
    ."\.([a-z]{2,}){1}$";
             if(!
    eregi($regex,$subemail)){
                
    $form->setError($field"* Email invalid");
             }
             
    $subemail stripslashes($subemail);
          }
          
          
    /* Errors exist, have user correct them */
          
    if($form->num_errors 0){
             return 
    false;  //Errors with form
          
    }
          
          
    /* Update password since there were no errors */
          
    if($subcurpass && $subnewpass){
             
    $database->updateUserField($this->username,"password",md5($subnewpass));
          }
          
          
    /* Change Email */
          
    if($subemail){
             
    $database->updateUserField($this->username,"email",$subemail);
          }
          
          
    /* Success! */
          
    return true;
       }
       
       
    /**
        * isAdmin - Returns true if currently logged in user is
        * an administrator, false otherwise.
        */
       
    function isAdmin(){
          return (
    $this->userlevel == ADMIN_LEVEL ||
                  
    $this->username  == ADMIN_NAME);
       }
       
       
    /**
        * generateRandID - Generates a string made up of randomized
        * letters (lower and upper case) and digits and returns
        * the md5 hash of it to be used as a userid.
        */
       
    function generateRandID(){
          return 
    md5($this->generateRandStr(16));
       }
       
       
    /**
        * generateRandStr - Generates a string made up of randomized
        * letters (lower and upper case) and digits, the length
        * is a specified parameter.
        */
       
    function generateRandStr($length){
          
    $randstr "";
          for(
    $i=0$i<$length$i++){
             
    $randnum mt_rand(0,61);
             if(
    $randnum 10){
                
    $randstr .= chr($randnum+48);
             }else if(
    $randnum 36){
                
    $randstr .= chr($randnum+55);
             }else{
                
    $randstr .= chr($randnum+61);
             }
          }
          return 
    $randstr;
       }
       
       function 
    userNotifications()
       {
               global 
    $database;
            
             
    /* get notifications */
             
    $database->getNotifications($this->username,$this->lastlogin,$this->townid);
            

            
       }
    };


    /**
     * Initialize session object - This must be initialized before
     * the form object because the form uses session variables,
     * which cannot be accessed unless the session has started.
     */
    $session = new Session;

    /* Initialize form object */
    $form = new Form;

    ?>
    i have created a new function to try and run a query and return the number of rows
    PHP Code:
       function userNotifications()
       {
               global 
    $database;
            
             
    /* get notifications */
             
    $database->getNotifications($this->username,$this->lastlogin,$this->townid);        
       } 
    below i will post the database.php file and the function i created in there

  • #3
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    database.php file
    PHP Code:
    <?php
    /**
     * Database.php
     * 
     * The Database class is meant to simplify the task of accessing
     * information from the website's database.
     *
     * Please subscribe to our feeds at http://blog.geotitles.com for more such tutorials
     */
    include("constants.php");
          
    class 
    MySQLDB
    {
       var 
    $connection;         //The MySQL database connection
       
    var $num_active_users;   //Number of active users viewing site
       
    var $num_active_guests;  //Number of active guests viewing site
       
    var $num_members;        //Number of signed-up users
       /* Note: call getNumMembers() to access $num_members! */

       /* Class constructor */
       
    function MySQLDB(){
          
    /* Make connection to database */
          
    $this->connection mysql_connect(DB_SERVERDB_USERDB_PASS) or die(mysql_error());
          
    mysql_select_db(DB_NAME$this->connection) or die(mysql_error());
          
          
    /**
           * Only query database to find out number of members
           * when getNumMembers() is called for the first time,
           * until then, default value set.
           */
          
    $this->num_members = -1;
          
          if(
    TRACK_VISITORS){
             
    /* Calculate number of users at site */
             
    $this->calcNumActiveUsers();
          
             
    /* Calculate number of guests at site */
             
    $this->calcNumActiveGuests();
          }
       }

       
    /**
        * confirmUserPass - Checks whether or not the given
        * username is in the database, if so it checks if the
        * given password is the same password in the database
        * for that user. If the user doesn't exist or if the
        * passwords don't match up, it returns an error code
        * (1 or 2). On success it returns 0.
        */
       
    function confirmUserPass($username$password){
          
    /* Add slashes if necessary (for query) */
          
    if(!get_magic_quotes_gpc()) {
              
    $username addslashes($username);
          }

          
    /* Verify that user is in database */
          
    $q "SELECT password FROM ".TBL_USERS." WHERE username = '$username'";
          
    $result mysql_query($q$this->connection);
          if(!
    $result || (mysql_numrows($result) < 1)){
             return 
    1//Indicates username failure
          
    }

          
    /* Retrieve password from result, strip slashes */
          
    $dbarray mysql_fetch_array($result);
          
    $dbarray['password'] = stripslashes($dbarray['password']);
          
    $password stripslashes($password);

          
    /* Validate that password is correct */
          
    if($password == $dbarray['password']){
             return 
    0//Success! Username and password confirmed
          
    }
          else{
             return 
    2//Indicates password failure
          
    }
       }
       
       
    /**
        * confirmUserID - Checks whether or not the given
        * username is in the database, if so it checks if the
        * given userid is the same userid in the database
        * for that user. If the user doesn't exist or if the
        * userids don't match up, it returns an error code
        * (1 or 2). On success it returns 0.
        */
       
    function confirmUserID($username$userid){
          
    /* Add slashes if necessary (for query) */
          
    if(!get_magic_quotes_gpc()) {
              
    $username addslashes($username);
          }

          
    /* Verify that user is in database */
          
    $q "SELECT userid FROM ".TBL_USERS." WHERE username = '$username'";
          
    $result mysql_query($q$this->connection);
          if(!
    $result || (mysql_numrows($result) < 1)){
             return 
    1//Indicates username failure
          
    }

          
    /* Retrieve userid from result, strip slashes */
          
    $dbarray mysql_fetch_array($result);
          
    $dbarray['userid'] = stripslashes($dbarray['userid']);
          
    $userid stripslashes($userid);

          
    /* Validate that userid is correct */
          
    if($userid == $dbarray['userid']){
             return 
    0//Success! Username and userid confirmed
          
    }
          else{
             return 
    2//Indicates userid invalid
          
    }
       }
       
       
    /**
        * usernameTaken - Returns true if the username has
        * been taken by another user, false otherwise.
        */
       
    function usernameTaken($username){
          if(!
    get_magic_quotes_gpc()){
             
    $username addslashes($username);
          }
          
    $q "SELECT username FROM ".TBL_USERS." WHERE username = '$username'";
          
    $result mysql_query($q$this->connection);
          return (
    mysql_numrows($result) > 0);
       }
       
       
    /**
        * usernameBanned - Returns true if the username has
        * been banned by the administrator.
        */
       
    function usernameBanned($username){
          if(!
    get_magic_quotes_gpc()){
             
    $username addslashes($username);
          }
          
    $q "SELECT username FROM ".TBL_BANNED_USERS." WHERE username = '$username'";
          
    $result mysql_query($q$this->connection);
          return (
    mysql_numrows($result) > 0);
       }
       
       
    /**
        * addNewUser - Inserts the given (username, password, email)
        * info into the database. Appropriate user level is set.
        * Returns true on success, false otherwise.
        */
       
    function addNewUser($username$password$email$fname$lname){
          
    $time time();
          
    /* If admin sign up, give admin user level */
          
    if(strcasecmp($usernameADMIN_NAME) == 0){
             
    $ulevel ADMIN_LEVEL;
          }else{
             
    $ulevel USER_LEVEL;
          }
          
    $q "INSERT INTO ".TBL_USERS." VALUES ('$email', '$fname', '$lname','$password', '0', $ulevel, '$email', $time)";
          return 
    mysql_query($q$this->connection);
       }
       
       
    /**
        * updateUserField - Updates a field, specified by the field
        * parameter, in the user's row of the database.
        */
       
    function updateUserField($username$field$value){
          
    $q "UPDATE ".TBL_USERS." SET ".$field." = '$value' WHERE username = '$username'";
          return 
    mysql_query($q$this->connection);
       }
       
       
    /**
        * getUserInfo - Returns the result array from a mysql
        * query asking for all information stored regarding
        * the given username. If query fails, NULL is returned.
        */
       
    function getUserInfo($username){
          
    $q "SELECT * FROM ".TBL_USERS." WHERE username = '$username'";
          
    $result mysql_query($q$this->connection);
          
    /* Error occurred, return given name by default */
          
    if(!$result || (mysql_numrows($result) < 1)){
             return 
    NULL;
          }
          
    /* Return result array */
          
    $dbarray mysql_fetch_array($result);
          return 
    $dbarray;
       }
       
       
    /**
        * getNumMembers - Returns the number of signed-up users
        * of the website, banned members not included. The first
        * time the function is called on page load, the database
        * is queried, on subsequent calls, the stored result
        * is returned. This is to improve efficiency, effectively
        * not querying the database when no call is made.
        */
       
    function getNumMembers(){
          if(
    $this->num_members 0){
             
    $q "SELECT * FROM ".TBL_USERS;
             
    $result mysql_query($q$this->connection);
             
    $this->num_members mysql_numrows($result);
          }
          return 
    $this->num_members;
       }
       
       
    /**
        * calcNumActiveUsers - Finds out how many active users
        * are viewing site and sets class variable accordingly.
        */
       
    function calcNumActiveUsers(){
          
    /* Calculate number of users at site */
          
    $q "SELECT * FROM ".TBL_ACTIVE_USERS;
          
    $result mysql_query($q$this->connection);
          
    $this->num_active_users mysql_numrows($result);
       }
       
       
    /**
        * calcNumActiveGuests - Finds out how many active guests
        * are viewing site and sets class variable accordingly.
        */
       
    function calcNumActiveGuests(){
          
    /* Calculate number of guests at site */
          
    $q "SELECT * FROM ".TBL_ACTIVE_GUESTS;
          
    $result mysql_query($q$this->connection);
          
    $this->num_active_guests mysql_numrows($result);
       }
       
       
    /**
        * addActiveUser - Updates username's last active timestamp
        * in the database, and also adds him to the table of
        * active users, or updates timestamp if already there.
        */
       
    function addActiveUser($username$time){
          
    $q "UPDATE ".TBL_USERS." SET timestamp = '$time' WHERE username = '$username'";
          
    mysql_query($q$this->connection);
          
          if(!
    TRACK_VISITORS) return;
          
    $q "REPLACE INTO ".TBL_ACTIVE_USERS." VALUES ('$username', '$time')";
          
    mysql_query($q$this->connection);
          
    $this->calcNumActiveUsers();
       }
       
       
    /* addActiveGuest - Adds guest to active guests table */
       
    function addActiveGuest($ip$time){
          if(!
    TRACK_VISITORS) return;
          
    $q "REPLACE INTO ".TBL_ACTIVE_GUESTS." VALUES ('$ip', '$time')";
          
    mysql_query($q$this->connection);
          
    $this->calcNumActiveGuests();
       }
       
       
    /* These functions are self explanatory, no need for comments */
       
       /* removeActiveUser */
       
    function removeActiveUser($username){
          if(!
    TRACK_VISITORS) return;
          
    $q "DELETE FROM ".TBL_ACTIVE_USERS." WHERE username = '$username'";
          
    mysql_query($q$this->connection);
          
    $this->calcNumActiveUsers();
       }
       
       
    /* removeActiveGuest */
       
    function removeActiveGuest($ip){
          if(!
    TRACK_VISITORS) return;
          
    $q "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE ip = '$ip'";
          
    mysql_query($q$this->connection);
          
    $this->calcNumActiveGuests();
       }
       
       
    /* removeInactiveUsers */
       
    function removeInactiveUsers(){
          if(!
    TRACK_VISITORS) return;
          
    $timeout time()-USER_TIMEOUT*60;
          
    $q "DELETE FROM ".TBL_ACTIVE_USERS." WHERE timestamp < $timeout";
          
    mysql_query($q$this->connection);
          
    $this->calcNumActiveUsers();
       }

       
    /* removeInactiveGuests */
       
    function removeInactiveGuests(){
          if(!
    TRACK_VISITORS) return;
          
    $timeout time()-GUEST_TIMEOUT*60;
          
    $q "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE timestamp < $timeout";
          
    mysql_query($q$this->connection);
          
    $this->calcNumActiveGuests();
       }
       
       
    /**
        * query - Performs the given query on the database and
        * returns the result, which may be false, true or a
        * resource identifier.
        */
       
    function query($query){
          return 
    mysql_query($query$this->connection);
       }
       
       
        function 
    getNotifications($username,$lastlogin,$town)
        {
            
    $q "SELECT * FROM ".TBL_JOBS." WHERE DATE(createdDate) >= $lastlogin";
            
    $result mysqli_query($this->connection,$q)or die(mysqli_error());
            
    $rows mysql_num_rows($result);
            return 
    $rows;
        }   
        
        function 
    updateLastLogin($username$time)
        {
            
    $q "UPDATE ".TBL_USERS." SET lastlogin = $time WHERE username = '$username'";
            echo 
    $q;
            
    $result mysql_query($q,$this->connection)or die(mysql_error());
        }
    };

    /* Create database connection */
    $database = new MySQLDB;

    ?>
    and the function i created in there is
    PHP Code:
        function getNotifications($username,$lastlogin,$town)
        {
            
    $q "SELECT * FROM ".TBL_JOBS." WHERE DATE(createdDate) >= $lastlogin";
            
    $result mysqli_query($this->connection,$q)or die(mysqli_error());
            
    $rows mysql_num_rows($result);
            return 
    $rows;
        } 

  • #4
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    so going back to my login.php page

    PHP Code:
                    <span class="notification-counter">
                    <?php $session->userNotifications;?>
                    </span>
    is currently returning
    Notice: Undefined property: Session::$userNotifications in C:\wamp\www\ecornwall2\login.php on line 71

    but im not experienced enough with oop to know what is wrong?

    if anyone could help me to understand the relationship between the session.php and the database.php files and why am am seeing the error and not the resut of the query?

    many thanks
    Luke

  • #5
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    This is super oldschool code. You shouldn't really use this as its not designed for PHP 5+, and it won't actually work if you namespace the class ending it with the 'Session' (ie: namespace custom\Session) since they broke the BC to not work with constructions against the same ending namespace.

    The sessions is calling via a property, which is incorrect. You need to call it as a method, so add the () to it.
    The connection won't work. Your mixing mysqli and mysql libraries which you cannot do. You should also use a count and not a num_rows; num_rows will require you to fetch every record into memory, a count needs to simply count.

    You should abandon these classes asap and find something newer. Chances are you've written based on these classes already though, which means you'll probably be better of rewriting it by hand instead.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #6
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    ah crap

    don't suppose you know of any newer login scripts around do you?

    Thanks

  • #7
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    Can't say I do (I don't really need to download any classes I need ).
    You can use the same search criteria you previously did, but add PHP5+ on it and it'll hopefully remove the old PHP 4.x version classes. 4.x isn't really OO and had a substantially. . . hack and slash methodology to make it work.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #8
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    ok i have searched google and cant find anything that is suitable, either they use PDO databases or they are just very outdated

    how easy would it be to update my current script?

  • #9
    Senior Coder CFMaBiSmAd's Avatar
    Join Date
    Oct 2006
    Location
    Denver, Colorado USA
    Posts
    2,960
    Thanks
    2
    Thanked 304 Times in 296 Posts
    The biggest problems with the current code is its naming and organization. Its organization looks like someone took some procedural code, split it up, and wrapped class/method definitions around it. This is also a reason why there are multiple global $database; statements in it, it wasn't really written from the ground up as good OOP code.

    The session class is actually a user class. The properties and methods in it are things relating to a user.

    The database class is actually a collection of user database-support functions, who's functionality belongs in the user class. This would eliminate need for the global $database; statements, which are generally a clue that the code is not organized correctly.

    The code does need a general purpose database class, but the only things it should do is provided methods/properties needed to run the query statements it is given, check for errors, and retrieve and return the data from the query.

    You would be much better off to simply define what you want your class to do, then write the methods that you need (this will also teach you the difference between calling a class's method and referencing a class's property), rather than trying to find good code on the Internet that does what you want.
    If you are learning PHP, developing PHP code, or debugging PHP code, do yourself a favor and check your web server log for errors and/or turn on full PHP error reporting in php.ini or in a .htaccess file to get PHP to help you.

  • #10
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    I totally agree, i would learn so much if i coded this myself but i wouldn't know where to start

    im guessing i need at least 2 classes

    1/database
    2/user

    database:
    connect to the db
    check login (if username/password is correct)
    keep track of guests/members
    get number of members

    user
    check if logged in or not
    check if username exists
    add new user
    update users last login
    delete user
    ban user

    thats a list off the top of my head (im sure i've missed many) of what i want the classes to do?

    what else am i missing, would you agree with the above?

    do i need a session class like in the current script?

    sorry for the endless questions but this is all new to me but im keen to learn it, and learn it properly

    thanks for your help
    Luke
    Last edited by LJackson; 10-05-2013 at 11:33 PM.

  • #11
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    ok so i am going to 'try' and get a basic database class done

    wish me luck i am going to need it :P

    will post back when i hopefully have something working

  • #12
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    ok im starting to realise that this is way out of my league

    i have started on a db class (not got very far tho)
    PHP Code:
    class db
    {
        private 
    $connection;
        private 
    $selectdb;
        private 
    $config;

        function 
    __construct($config)
        {
            
    $this->config $config;
        }
        
        function 
    __destruct()
        {
            
        }

        public function 
    openConnection()
        {
                    
    $this->connection mysqli_connect($this->config->hostname$this->config->username$this->config->password);
                    
    $this->selectdb mysqli_select_db($this->connection$this->config->database);
        }

        public function 
    closeConnection()
        {
            
    mysqli_close($this->connection);
        }
        

    and i have a config class
    PHP Code:
    class config
    {
        public 
    $hostname;
        public 
    $username;
        public 
    $password;
        public 
    $database;
        
        function 
    __construct($hostname NULL$username NULL$password NULL$database NULL)
        {
            
    $this->hostname = !empty($hostname) ? $hostname "";
            
    $this->username = !empty($username) ? $username "";
            
    $this->password = !empty($password) ? $password "";
            
    $this->database = !empty($database) ? $database "";
        }
        
        function 
    __destruct()
        {
            
        }

    and im using these in my php page like so
    PHP Code:
    <?php
    //including the classes.
    include("classes/database.php");
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    </head>

    <body>
    <?php
        
        
    // We need to have 1 config object with all data in.
        
    $config = new config("hostname""username""password""database"); //type in your data here…

        // Now we need to have access to the db class, we uses the config object to configure the db object.
        
    $db = new db($config);

        
    // We can now open the connection to the database.
        
    $db->openConnection();

    ?>
    </body>
    </html>
    before i go any further is this the best/correct way to go about this? i've looked online and i havent come across two sites that say suggest the same method

    thanks
    Luke

  • #13
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,979
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    Depends on your definition of "best".
    I myself have a very complex methodology which decouples my objects as much as is potentially possible, and uses a proxy via dependency management to inject into other class objects. This is a relatively complicated methodology (which becomes easy as time passes).
    Aside from coupling, there is no issue with what you are doing. It is perfectly legal and logical to assemble an object from other objects; however, using a separate config class and presenting it to a db class may not be the best solution. The reason why is simple; the db class is not generic, so having a separate config doesn't make a whole lot of sense since it'll be designed only to work with MySQLi. A factory may be easier to work with. For an example:
    PHP Code:
    interface IDatastore
    {
        public function 
    __construct(IConfig $config);
        public function 
    open();
        public function 
    close();
    }

    interface 
    IConfig
    {
        public function 
    getProperty($sProperty);
        public function 
    setProperty($sProperty$mValue);
    }

    class 
    Config implements IConfig
    {
        private 
    $aProperties = array();

        public function 
    getProperty($sProperty)
        {
            return isset(
    $this->aProperties[$sProperty]) ? $this->aProperties[$sProperty] : null;
        }

        public function 
    setProperty($sProperty$mValue)
        {
            
    $this->aProperties[$sProperty] = $mValue;
        }
    }

    class 
    DatastoreFactory
    {
        private function 
    __construct(){}

        public static function 
    create(IConfig $config)
        {
            
    $sDriver $config->getProperty('driver');
            if (
    $sDriver == null)
            {
                throw new 
    Exception('Driver is not valid');
            }

            return new 
    $sDriver($config);
        }
    }

    class 
    MySQLiDriver implements IDatastore
    {
        private 
    $config;

        public function 
    __construct(IConfig $config)
        {
            
    $this->config $config;
        }

        public function 
    open()
        {
            
    printf("%s(user: %s, password: %s, db: %s)" PHP_EOL,
                
    __METHOD__,
                
    $this->config->getProperty('user'),
                
    $this->config->getProperty('password'),
                
    $this->config->getProperty('db')
            );
        }

        public function 
    close()
        {
            print 
    __METHOD__;
        }
    }

    $config = new Config();
    $config->setProperty('driver''mysqlidriver');
    $config->setProperty('user''mysqluser');
    $config->setProperty('password''mysqlpassword');
    $config->setProperty('db''mysqldb');
    $db DatastoreFactory::create($config);
    $db->open(); 
    You can write whatever drivers you want. If this were real, I'd actually use a much more useful IConfig than what's there, but a simple set/get is easy for an example.

    Also, never use public properties in PHP. Since its datatype weak, you never want free reign to read and write into it. Yes you can lift an accessor from a property through reflection, but I'd assume the developer knows what they're doing then.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #14
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    thanks for the example mate, on first reflection it does look complex (tho im sure it will understand it better the more i learn oop )

    I have extended my db class to include some basic functions
    PHP Code:
    class db
    {
        private 
    $connection;
        private 
    $selectdb;
        private 
    $lastQuery;
        private 
    $config;

        function 
    __construct($config)
        {
            
    $this->config $config;
        }
        
        function 
    __destruct()
        {
            
        }

        public function 
    openConnection()
        {
            
    $this->connection mysqli_connect($this->config->hostname$this->config->username$this->config->password);
            
    $this->selectdb mysqli_select_db($this->connection$this->config->database);
        }

        public function 
    closeConnection()
        {
            
    mysqli_close($this->connection);
        }
        
        public function 
    ecapeString($string)
        {
            return 
    addslashes($string);
        }

        public function 
    query($query)
        {
            if(empty(
    $this->connection))
            {
                
    $this->openConnection();
                
    $this->lastQuery mysqli_query($this->connection$this->ecapeString($query));
                
    $this->closeConnection();
                return 
    $this->lastQuery;
            }
            else
            {
                
    $this->lastQuery mysqli_query($this->connection$this->ecapeString($query));
                return 
    $this->lastQuery;
            }
        }

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

        public function 
    pingServer()
        {
            if(!
    mysqli_ping($this->connection))
            {
                return 
    false;
            }
            else
            {
                return 
    true;
            }
        }
        
        public function 
    hasRows($result)
        {
            if(
    mysqli_num_rows($result)>0)
            {
                return 
    true;
            }
            else
            {
                return 
    false;
            }
        }
        
        public function 
    countRows($result)
        {
            return 
    mysqli_num_rows($result);
        }
        
        public function 
    fetchAssoc($result)
        {
            return 
    mysqli_fetch_assoc($result);
        }
        
        public function 
    fetchArray($result)
        {
            return 
    mysqli_fetch_array($result);
        }

    am i still on the correct lines? and if i am(which i doubt i am ) my next step would be to create the other functions which are specific to my project.

    would things like checking the users login details be stored in the database class or a user class?

    thanks

  • #15
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    right i am trying to get a function to work which check the users password is correct
    PHP Code:
           function confirmUserPass($username$password)
        {
            
    /* Add slashes if necessary (for query) */
            
    if(!get_magic_quotes_gpc())
            {
                
    $username addslashes($username);
            }
        
            
    /* Verify that user is in database */
            
    $q $this->query("SELECT password FROM ".TBL_USERS." WHERE username = '$username'");
            if(!
    $q || ($this->hasRows($q) == 0))//if there are NO rows
            
    {
               return 
    1//Indicates username failure
            
    }
        
            
    /* Retrieve password from result, strip slashes */
            
    $dbarray $this->fetchArray($result);
            
    $dbarray['password'] = stripslashes($dbarray['password']);
            
    $password stripslashes($password);
        
            
    /* Validate that password is correct */
            
    if($password == $dbarray['password'])
            {
                return 
    0//Success! Username and password confirmed
            
    }
            else
            {
                return 
    2//Indicates password failure
            
    }
        } 
    the current problem is that it is throwing an error
    Code:
     mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given
    im guessing its because the hasRows function returns true or false?

    EDIT
    ===

    Seems like the problem was with this line of the query function
    PHP Code:
    $this->lastQuery mysqli_query($this->connection$this->ecapeString($query)) 
    changed it to
    PHP Code:
    $this->lastQuery mysqli_query($this->connection$query
    and it now 'seems' to be working
    Last edited by LJackson; 10-08-2013 at 06:13 PM.


  •  
    Page 1 of 3 123 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •