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 2 of 3 FirstFirst 123 LastLast
Results 16 to 30 of 41
  1. #16
    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
    The escape is wrong; addslashes is insufficient for escaping sql syntax. Use the mysqli_real_escape_string.
    I wouldn't return the resultset from a query. Since its already in the class and assigned to a property, you can just use it directly in. That would also mean you do not need to provide an argument to the fetches.
    You should probably consider not opening and closing within internal function calls. Let the external calls dictate those. You can add a property to recall if its open, and use that as a part of the __destruct. Otherwise, just remove the destruct since it has no body anyway.

    Edit:
    Since you got another in there.
    You cannot just call escapeString on a SQL string. It can only be called on the arguments provided for it, otherwise it will escape your actual structure. Although you'd have to write it by hand yourself, especially so its compatible with any other driver, you could write it as prepared statements and completely eliminate that issue.
    Last edited by Fou-Lu; 10-08-2013 at 06:21 PM.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  2. #17
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    I wouldn't return the resultset from a query. Since its already in the class and assigned to a property, you can just use it directly in. That would also mean you do not need to provide an argument to the fetches.
    can you show me what you mean please?

    You should probably consider not opening and closing within internal function calls. Let the external calls dictate those.
    again could you show me please?

    you could write it as prepared statements and completely eliminate that issue.
    prepared statements are something i have come ac ross but yet dont know how to use them.

    sorry for not following 100% im sure i'll get it one day

    thanks
    Luke

  3. #18
    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
    Simply remove the openConnection and closeConnection calls within the query.
    PHP Code:
    public function query($query)
    {
        if (
    $this->connection == null)
        {
            throw new 
    RuntimeException('Connection not established');
        }
        
    $this->lastQuery mysqli_query($this->connection$query);

    Fetching doesn't require a resultset since the lastquery is a member property:
    PHP Code:
    public function fetch()
    {
        return 
    mysqli_fetch_assoc($this->lastQuery);

    Still valid in a loop since it'll return null when its done.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  4. Users who have thanked Fou-Lu for this post:

    LJackson (10-08-2013)

  5. #19
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    ok i have my classes setup

    i have
    a database class -> for database related functions
    a user class -> for user related functions
    a session class -> to start the sessions and to see if the user is logged in etc
    a form class -> to handle form processing
    a mailer class -> to deal with mailing the user

    would appreaciate it if you could have a quick look through them and check if they are ok and to see if the functions are in the correct classes

    firstly my database class
    PHP Code:
    #DATABASE CLASS
    include("constants.php");

    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);
            
              
    /**
               * 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();
              }
        }

        public function 
    closeConnection()
        {
            
    mysqli_close($this->connection);
        }
        
        public function 
    query($query)
        {
            if (
    $this->connection == null)
            {
                throw new 
    RuntimeException('Connection not established');
            }
            
    $this->lastQuery mysqli_query($this->connection$query);
            return 
    $this->lastQuery;
        }      
        
        public function 
    lastQuery()
        {
            return 
    $this->lastQuery;
        }
        
        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()
        {
            return 
    mysqli_fetch_assoc($this->lastQuery);
        }
        
        public function 
    fetchArray()
        {
            return 
    mysqli_fetch_array($this->lastQuery);
        }
        
        public function 
    realEscape($result)
        {
            return 
    mysqli_real_escape_string($this->connection,$result);
        }
        
           
    /**
        * 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 $this->realEscape($username);
            }

            
    /* Verify that user is in database */
            
    $q "SELECT password FROM ".TBL_USERS." WHERE username = '$username'";
            
    $result $this->query($q);
            if(!
    $result || $this->hasRows($result) < 1)
            {
               return 
    1//Indicates username failure
            
    }
        
            
    /* Retrieve password from result, strip slashes */
            
    $dbarray $this->fetchArray();
            
    /* 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 $this->realEscape($username);
              }

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

              
    /* Retrieve userid from result, strip slashes */
              
    $dbarray $this->fetchArray();
              
    $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 $this->realEscape($username);
              }
              
    $q "SELECT username FROM ".TBL_USERS." WHERE username = '$username'";
              
    $result $this->query($q);
              return (
    $this->countRows($result) > 0);
           }
       
           
    /**
        * usernameBanned - Returns true if the username has
        * been banned by the administrator.
        */
           
    function usernameBanned($username)
        {
              if(!
    get_magic_quotes_gpc())
              {
                 
    $username $this->realEscape($username);
              }
              
    $q "SELECT username FROM ".TBL_BANNED_USERS." WHERE username = '$username'";
              
    $result $this->query($q);
              return (
    $this->countRows($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($email$password$fname$lname)
        {
              
    $time time();
              
    /* If admin sign up, give admin user level */
              
    if(strcasecmp($emailADMIN_NAME) == 0)
            {
                
    $ulevel ADMIN_LEVEL;
              }
            else
            {
                
    $ulevel USER_LEVEL;
              }
              
    $q "INSERT INTO ".TBL_USERS." (username,firstname,surname,password,userid,userlevel,email,timestamp) 
            VALUES ('$email', '$fname', '$lname','$password','','$ulevel','$email','$time')"
    ;
              return 
    $this->query($q);
       }
        
       
    /**
        * 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 $this->query($q);
                
    $this->num_members $this->countRows($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 $this->query($q);
              
    $this->num_active_users $this->countRows($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 $this->query($q);
              
    $this->num_active_guests $this->countRows($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'";
              
    $this->query($q);
          
              if(!
    TRACK_VISITORS) return;
              
    $q "REPLACE INTO ".TBL_ACTIVE_USERS." VALUES ('$username', '$time')";
              
    $this->query($q);
              
    $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')";
            
    $this->query($q);
              
    $this->calcNumActiveGuests();
       }

           
    /* removeActiveUser */
           
    function removeActiveUser($username)
        {
             if(!
    TRACK_VISITORS) return;
              
    $q "DELETE FROM ".TBL_ACTIVE_USERS." WHERE username = '$username'";
              
    $this->query($q);
              
    $this->calcNumActiveUsers();
           }
       
           
    /* removeActiveGuest */
           
    function removeActiveGuest($ip)
        {
              if(!
    TRACK_VISITORS) return;
              
    $q "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE ip = '$ip'";
              
    $this->query($q);
              
    $this->calcNumActiveGuests();
           }
       
           
    /* removeInactiveUsers */
           
    function removeInactiveUsers()
        {
              if(!
    TRACK_VISITORS) return;
              
    $timeout time()-USER_TIMEOUT*60;
              
    $q "DELETE FROM ".TBL_ACTIVE_USERS." WHERE timestamp < $timeout";
              
    $this->query($q);
              
    $this->calcNumActiveUsers();
           }

           
    /* removeInactiveGuests */
           
    function removeInactiveGuests()
        {
              if(!
    TRACK_VISITORS) return;
              
    $timeout time()-GUEST_TIMEOUT*60;
              
    $q "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE timestamp < $timeout";
              
    $this->query($q);
              
    $this->calcNumActiveGuests();
           }
        
        function 
    getNotifications($username)
        {
            
    $q "SELECT * FROM ".TBL_USERS." WHERE username = '$username'";
            
    $result $this->query($q);
            while(
    $row=$this->fetchArray($result))
            {
                
    $townID $row['placeID'];
                
    $lastlogin $row['lastlogin'];
            }
            
    $q "SELECT * FROM ".TBL_JOBS." as jobs LEFT JOIN tbl_job_location as joblocation ON jobs.jobID = joblocation.jobID WHERE DATE(createdDate) >= '$lastlogin' AND placeID = $townID";
            
    $result $this->query($q);
            
    $rows $this->countRows($result);
            return 
    $rows;
        }   
        
        function 
    updateLastLogin($username$time)
        {
            
    $q "UPDATE ".TBL_USERS." SET lastlogin = $time WHERE username = '$username'";
            
    $this->query($q);
        }
        
        function 
    showJobDetails($jobID)
        {
            
    $q "SELECT *
            FROM tbl_jobs AS job
            LEFT JOIN tbl_job_department AS jdept ON job.jobID = jdept.jobID
            LEFT JOIN tbl_departments as dept ON jdept.deptID = dept.deptID 
            LEFT JOIN tbl_job_location AS loc ON job.jobID = loc.jobID
            LEFT JOIN tbl_places AS place ON loc.placeID = place.placeID
            LEFT JOIN tbl_job_position AS jpos ON job.jobID = jpos.jobID 
            LEFT JOIN tbl_positions AS pos ON pos.positionID = jpos.positionID 
            WHERE job.jobID = '$jobID'"
    ;
            
    $query $this->query($q);
            while(
    $row=$this->fetchArray($query))
            {
                
    $title $row['jobTitle'];
                
    $desc $row['jobDesc'];
                
    $placeID $row['placeID'];
                
    $placeName $row['placeName'];
                
    $department $row['deptName'];
                
    $type $row['position'];
                
    $paymentType $row['paymentType'];
                
    $salary $row['salary'];
                
    $hoursPW $row['jobHoursPW'];
            }
        }
        
        function 
    showDepartments()
        {
            
    $q "SELECT * FROM ".TBL_DEPARTMENTS;
            
    $query $this->query($q);
            return 
    $query;
        }    
        

    am i right in saying the _destruct function is the last thing called when the database or any other class is used by default? if so is it a good idea to have a mysqli_close($this->connection); in there and remove the closeConnection() altogether?

    hopefully i am on the right lines?

    cheers
    Luke
    Last edited by LJackson; 10-09-2013 at 04:29 PM.

  6. #20
    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
    No destruct is called when the object is destroyed. It is rarely required; in a connection class it may be wise to see if the connection is open, and if so tear it down. Don't try to close it if its already closed.
    countRows, foundrows, etc, all can use the internal member property. Don't accept an argument.

    I'm confused here, do you have multiple classes? This only has one class, but a bunch of methods in it that don't belong. A db class won't care about a user, or an email, or. . . it only cares about connections and executing queries.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  7. #21
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    ah ok thanks i understand the _destruct now

    have changed the countRows hasRows and removed the arguments so it now just returns the result

    I'm confused here, do you have multiple classes? This only has one class, but a bunch of methods in it that don't belong. A db class won't care about a user, or an email, or. . . it only cares about connections and executing queries.
    lol so am i i have 5 classes in all each have there own php page.

    They are:
    a database class -> for database related functions
    a user class -> for user related functions
    a session class -> to start the sessions and to see if the user is logged in etc
    a form class -> to handle form processing
    a mailer class -> to deal with mailing the user

    the reason for having some user methods in the databse class is because it involves the databse i thought it best go in there and not in the user class?

    my user class does stuff like login the user, edit user profile, register the user, change the users password etc

    the user class (user.php)
    PHP Code:
    <?php
    include("database.php");
    include(
    "session.php");
    include(
    "mailer.php");
    include(
    "form.php");

    class 
    user()
    {

        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.
        */
           /**
        * 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$session;  //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 */
              
    $session->userinfo  $database->getUserInfo($subuser);
              
    $session->username  $_SESSION['username'] = $session->userinfo['username'];
              
    $session->userid    $_SESSION['userid']   = $session->generateRandID();
              
    $session->userlevel $session->userinfo['userlevel'];
          
              
    /* Insert userid into database and update active users table */
              
    $database->updateUserField($session->username"userid"$session->userid);
              
    $database->addActiveUser($session->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"$session->usernametime()+COOKIE_EXPIRECOOKIE_PATH);
                 
    setcookie("cookid",   $session->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$session;  //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 */
              
    $session->logged_in false;
          
              
    /**
               * Remove from active users table and add to
               * active guests tables.
               */
              
    $database->removeActiveUser($session->username);
              
    $database->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
          
              
    /* Update Last Login IN User table */
              
    $database->updateLastLogin($session->username$this->time);
          
              
    /* Set user level to guest */
              
    $session->username  GUEST_NAME;
              
    $session->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($subemailmd5($subpass), $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($session->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($session->username,"password",md5($subnewpass));
              }
          
              
    /* Change Email */
              
    if($subemail)
            {
                 
    $database->updateUserField($session->username,"email",$subemail);
              }
          
              
    /* Success! */
              
    return true;
           }
       
           
    /**
        * isAdmin - Returns true if currently logged in user is
        * an administrator, false otherwise.
        */
           
    function isAdmin()
        {
              return (
    $session->userlevel == ADMIN_LEVEL || $session->username  == ADMIN_NAME);
          }
        
           function 
    userNotifications()
           {
               global 
    $database;
            
            
    /* get notifications */
            
    $database->getNotifications($session->username,$session->lastlogin,$session->townid);
           }
    }
    ?>

  8. #22
    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
    Nope, never put something in a class that doesn't belong. It defeats the purpose of the class and cannot be reused elsewhere.
    Also, never use global in an object unless there is absolutely no alternatives. If you think global is bad with procedural code, wait until it needs to be debugged in OO code.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  9. #23
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    oh ok,

    so if i remove everything that queries the database and just have the database class like so
    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);
            
              
    /**
               * 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();
              }
        }

        public function 
    closeConnection()
        {
            
    mysqli_close($this->connection);
        }
        
        public function 
    query($query)
        {
            if (
    $this->connection == null)
            {
                throw new 
    RuntimeException('Connection not established');
            }
            
    $this->lastQuery mysqli_query($this->connection$query);
            return 
    $this->lastQuery;
        }      
        
        public function 
    lastQuery()
        {
            return 
    $this->lastQuery;
        }
        
        public function 
    hasRows($result)
        {
            return 
    mysqli_num_rows($result);
        }
        
        public function 
    countRows($result)
        {
            return 
    mysqli_num_rows($result);
        }
        
        public function 
    fetchAssoc()
        {
            return 
    mysqli_fetch_assoc($this->lastQuery);
        }
        
        public function 
    fetchArray()
        {
            return 
    mysqli_fetch_array($this->lastQuery);
        }
        
        public function 
    realEscape($result)
        {
            return 
    mysqli_real_escape_string($this->connection,$result);
        }

    is that better?

    then with the other functions i have removed from there for example
    PHP Code:
           function confirmUserPass($username$password)
        {
            
    /* Add slashes if necessary (for query) */
            
    if(!get_magic_quotes_gpc())
            {
                
    $username $this->realEscape($username);
            }

            
    /* Verify that user is in database */
            
    $q "SELECT password FROM ".TBL_USERS." WHERE username = '$username'";
            
    $result $this->query($q);
            if(!
    $result || $this->hasRows($result) < 1)
            {
               return 
    1//Indicates username failure
            
    }
        
            
    /* Retrieve password from result, strip slashes */
            
    $dbarray $this->fetchArray();
            
    /* Validate that password is correct */
            
    if($password == $dbarray['password'])
            {
                return 
    0//Success! Username and password confirmed
            
    }
            else
            {
                return 
    2//Indicates password failure
            
    }
        } 
    should i put this in the user class? and edit it like so
    PHP Code:
           function confirmUserPass($username$password)
        {
            
    /* Add slashes if necessary (for query) */
            
    if(!get_magic_quotes_gpc())
            {
                
    $username $database->realEscape($username);
            }

            
    /* Verify that user is in database */
            
    $q "SELECT password FROM ".TBL_USERS." WHERE username = '$username'";
            
    $result $database->query($q);
            if(!
    $result || $database->hasRows($result) < 1)
            {
               return 
    1//Indicates username failure
            
    }
        
            
    /* Retrieve password from result, strip slashes */
            
    $dbarray $database->fetchArray();
            
    /* Validate that password is correct */
            
    if($password == $dbarray['password'])
            {
                return 
    0//Success! Username and password confirmed
            
    }
            else
            {
                return 
    2//Indicates password failure
            
    }
        } 
    thanks for your continued help, i really appreciate it (i may be slow but i get there in the end )

    Luke

  10. #24
    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
    Yep, but $database needs to be provided. You can gather that through many pattern techniques, but for a starter in OO, a simple composition makes the most sense.
    Create a private $database in the User class. Access it using the $this->database. Use a constructor such as:
    PHP Code:
    public function __construct(db $db)
    {
        
    $this->database $db;

    And invoked as:
    PHP Code:
    $db = new db($config);
    $user = new User($db); 
    Its a rigid design, but you gotta start somewhere with OO. $db in the above block would be used with anything requiring access to the $db.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  11. #25
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    sweet! im getting somewhere

    will put it all together tomorrow and see if it works as expected
    Luke

  12. #26
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    right i have tried to piece it all together but as expected i've hit a few speed bumps

    but im getting an error in the user class
    Code:
    Fatal error: Class 'db' not found in C:\wamp\www\login_script\classes\user.php on line 851
    851 is
    PHP Code:
    $db = new db($config); 
    and the construct function of the class is
    PHP Code:
        public function __construct(db $db)
        {
            
    $this->database $db;
            
    $this->time time();
              
    $this->startSession();

        } 
    any ideas why im getting the error?

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

  13. #27
    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
    You need to include the db file into this script before it will load. Its the same thing as if you needed to load a userdefined function.
    You can make use of the autoload or even better, the spl_autoload_register. Follow this one, there's an example for registering the autoload: http://php.net/manual/en/function.sp...d-register.php
    This is why you want to always have a specific directory (or tree, in the case of namespaced code), and a common ending suffix. I always use .class.php and .interface.php.

    Edit:
    Also, standard inclusion still applies. I can't actually recall what I did prior to namespaces, but I think I would have included the db into the user since i have a reliance on that and don't want to let the control handle that. I would instead use relative pathing to get there.
    Namespaces are easier since you just register the extension and base path. The use keyword is chained to the autoloader.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  14. #28
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    ah of course thank you

    now it says
    Code:
    Notice: Undefined variable: config in C:\wamp\www\login_script\classes\user.php on line 853
    the databse.php file is included at the top of the page?

    here is a stripped down version of my user.php file
    PHP Code:
    <?php
    include("database.php");

    class 
    user
    {

        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.
        */
        
        
    public function __construct(db $db)
        {
            
    $this->database $db;
            
    $this->time time();
              
    $this->startSession();

        }      
        
                
    }

    $db = new db($config);
    $user = new User($db);
    ?>
    yet the $config is being passed in the databse class.
    database.php
    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);
            
              
    /**
               * 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();
              }
        }

        public function 
    closeConnection()
        {
            
    mysqli_close($this->connection);
        }
        
        public function 
    query($query)
        {
            if (
    $this->connection == null)
            {
                throw new 
    RuntimeException('Connection not established');
            }
            
    $this->lastQuery mysqli_query($this->connection$query);
            return 
    $this->lastQuery;
        }      
        
        public function 
    lastQuery()
        {
            return 
    $this->lastQuery;
        }
        
        public function 
    hasRows($result)
        {
            return 
    mysqli_num_rows($result);
        }
        
        public function 
    countRows($result)
        {
            return 
    mysqli_num_rows($result);
        }
        
        public function 
    fetchAssoc()
        {
            return 
    mysqli_fetch_assoc($this->lastQuery);
        }
        
        public function 
    fetchArray()
        {
            return 
    mysqli_fetch_array($this->lastQuery);
        }
        
        public function 
    realEscape($result)
        {
            return 
    mysqli_real_escape_string($this->connection,$result);
        }
        
    }

    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()
        {
            
        }


  15. #29
    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
    Don't use the var keyword, and make sure you scope the methods as public (although the default is public).
    Separate the config class and give it its own file. You'll need to instantiate and populate that first. Unfortunately, you will need to either write a __get or you'll need to leave the member properties public since the db class reads the properties directly (undesirable).
    I'm not sure what this is:
    PHP Code:
              /**
               * 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();
              } 
    That will throw an exception when you use it. Remove the entire block; the names sound to be that of which would belong in a collection for a User class (which would be statically called OR a class designed as a collection of user).

    Also, don't put that runtime stuff in the user class file. Include the classes you need in a runnable file; the classes should be definition files only, don't put any runtime functionality into them, or they will reduce the re-usability of them.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  16. #30
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,088
    Thanks
    296
    Thanked 12 Times in 12 Posts
    making the methods public, does this include the construct and destruct methods?

    that code block counts the number of users online so that each time the connection is opened an entry is added to the databse (think i will move it to the user class )

    i have seperated the config class and saved it as config.php, included it in the database file and that error has now gone

    now its saying
    Code:
    Notice: Undefined variable: database in C:\wamp\www\login_script\classes\user.php on line 610
    
    Fatal error: Call to a member function realEscape() on a non-object in C:\wamp\www\login_script\classes\user.php on line 610
    line 610 is
    PHP Code:
    $username $database->realEscape($username); 
    and the method in the database class is
    PHP Code:
        public function realEscape($result)
        {
            return 
    mysqli_real_escape_string($this->connection,$result);
        } 
    seems strange why it says undefined varible database as its used many times in the class before that method.

    by runtime stuff do you mean the methods such as
    PHP Code:
        function showJobDetails($jobID)
        {
            
    $q "SELECT *
            FROM tbl_jobs AS job
            LEFT JOIN tbl_job_department AS jdept ON job.jobID = jdept.jobID
            LEFT JOIN tbl_departments as dept ON jdept.deptID = dept.deptID 
            LEFT JOIN tbl_job_location AS loc ON job.jobID = loc.jobID
            LEFT JOIN tbl_places AS place ON loc.placeID = place.placeID
            LEFT JOIN tbl_job_position AS jpos ON job.jobID = jpos.jobID 
            LEFT JOIN tbl_positions AS pos ON pos.positionID = jpos.positionID 
            WHERE job.jobID = '$jobID'"
    ;
            
    $query $database->query($q);
            while(
    $row=$database->fetchArray($query))
            {
                
    $title $row['jobTitle'];
                
    $desc $row['jobDesc'];
                
    $placeID $row['placeID'];
                
    $placeName $row['placeName'];
                
    $department $row['deptName'];
                
    $type $row['position'];
                
    $paymentType $row['paymentType'];
                
    $salary $row['salary'];
                
    $hoursPW $row['jobHoursPW'];
            }
        } 
    cheers
    Luke


 
Page 2 of 3 FirstFirst 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
  •