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 3 of 3 FirstFirst 123
Results 31 to 41 of 41
  1. #31
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,097
    Thanks
    297
    Thanked 12 Times in 12 Posts
    in the user class i have changed all the $database to $this->database and now im getting

    Code:
    Fatal error: Uncaught exception 'RuntimeException' with message 'Connection not established' in C:\wamp\www\login_script\classes\database.php:58 Stack trace: #0 C:\wamp\www\login_script\classes\user.php(612): db->query('SELECT userid F...') #1 C:\wamp\www\login_script\classes\user.php(98): user->confirmUserID('msd_karate_kid@...', 'afea4a9c3464a0f...') #2 C:\wamp\www\login_script\classes\user.php(42): user->checkLogin() #3 C:\wamp\www\login_script\classes\user.php(27): user->startSession() #4 C:\wamp\www\login_script\classes\user.php(851): user->__construct(Object(db)) #5 C:\wamp\www\login_script\signin.php(2): include('C:\wamp\www\log...') #6 {main} thrown in C:\wamp\www\login_script\classes\database.php on line 58


    should i be using $this->database-> or just $database->

    thanks

  2. #32
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Don't forget to open your $db
    Edit:
    . . . but not in the db class, I mean the caller. Particularly the main running script.
    Edit:
    And you use $this->database. PHP does not allow variable masking so anything as a class method or member must be accessed using $this, or ClassName:: if its static.

    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  3. #33
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,097
    Thanks
    297
    Thanked 12 Times in 12 Posts
    Quote Originally Posted by Fou-Lu View Post
    Don't forget to open your $db
    Edit:
    . . . but not in the db class, I mean the caller. Particularly the main running script.
    Edit:
    And you use $this->database. PHP does not allow variable masking so anything as a class method or member must be accessed using $this, or ClassName:: if its static.

    ah yes i havent passed my db details to the config class, obviously its not going to work

    having said that, i cant get it to work

    im thinking i need to pass the db details to the config class like so
    PHP Code:
    $config = new Config("localhost""root""""local"); 
    but i have added that in both my database.php and user.php (not in the class itself but directly underneath it) and it hasnt made any difference

    i have also tried to add the following to the top of my main login page
    PHP Code:
        // We need to have 1 config object with all data in.
        
    $config = new Config("localhost""root""""local"); //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(); 
    but again i still get the same error

    something so simple, grr

    thanks for your patience with me and for your help
    Luke

  4. #34
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    You should only be getting that if you are trying to issue a query before you've successfully opened.
    I don't know what this line means:
    but i have added that in both my database.php and user.php (not in the class itself but directly underneath it) and it hasnt made any difference
    db should have a reference to Config, but user should only have a reference to db. Neither should have runnable code in it.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  5. #35
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,097
    Thanks
    297
    Thanked 12 Times in 12 Posts
    Quote Originally Posted by Fou-Lu View Post
    I don't know what this line means:
    basically says i tried to add this line
    PHP Code:
    $config = new Config("localhost""root""""local"); 
    to my user.php page and the database.php page but didnt solve the problem.

    where would i place my database information so it can connect to my database.

    would i edit my config class to include the data like so
    PHP Code:
    <?php
    class Config
    {
        public 
    $hostname;
        public 
    $username;
        public 
    $password;
        public 
    $database;
        
        function 
    __construct($hostname "localhost"$username "root"$password ""$database "local")
        {
            
    $this->hostname = !empty($hostname) ? $hostname "";
            
    $this->username = !empty($username) ? $username "";
            
    $this->password = !empty($password) ? $password "";
            
    $this->database = !empty($database) ? $database "";
        }
             
        function 
    __destruct()
        {
                 
        }
            
    }
    ?>
    or do i add the following in my signin.php page
    PHP Code:
        // We need to have 1 config object with all data in.
        
    $config = new Config("localhost""root""""local"); //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(); 
    either way none each of them produce the same error as above

    could i possibly email you the files to you as im sure you will see the problem straight away?

    thankyou!!
    Luke

  6. #36
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    The very first thing you have to do is remove the runnable code from any of the class files. PHP is not a natively OO language, and as such you need at minimum one procedural call. That is where you will take care of establishing anything you need or passing things to objects that know what they need to do. That code will go in the signin.php script. $config can be declared in a global script and included if it makes it easier (as can $db if you use it frequently). You cannot do anything with the User class that relies on a database connection until the $db->openConnection is called (assuming $db is the same $db provide to the class User). You also cannot do anything if the closeConnection() method has been called.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  7. #37
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,097
    Thanks
    297
    Thanked 12 Times in 12 Posts
    ok firstly i've got it working but its probably not 100% correct but its working

    first thing i did was add the following line to the db _construct method
    PHP Code:
    $this->openConnection($config); 
    so now each time the database class was used it was forced to open a connection.

    i've also had to change this in the db class
    PHP Code:
    private $connection
    to
    PHP Code:
    public $connection
    because it was giving me a
    Code:
    Fatal error: Cannot access private property db::$connection
    any idea why?

    this then gave me lots of errors in my classes, where i was using an incorrect object ie i was using things like $database->method instead of $this->database->method which took me a while to fix, but i have.

    unfortunately i have used some global varibles in my classes to get it working which i will fix later.

    when you say
    The very first thing you have to do is remove the runnable code from any of the class files.
    do you mean all the methods that run queries etc? like this
    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 $this->database->query($q);
            while(
    $row=$this->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'];
            }
        } 
    Last edited by LJackson; 10-14-2013 at 10:48 AM.

  8. #38
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,097
    Thanks
    297
    Thanked 12 Times in 12 Posts
    I'm trying to modify my user class and provide access to the form class, i've looked at how you explained how to provide access to the database like so
    PHP Code:
    public function __construct(db $db)
    {
        
    $this->database $db;

    and invoked by
    PHP Code:
    $db = new db($config);
    $user = new User($db); 
    so i tried to add my form in the same way...
    my user class
    PHP Code:
    <?php
    include("include/database.php");
    include(
    "include/mailer.php");
    include(
    "include/form.php");

    include(
    "constants.php");

    class 
    user
    {
        var 
    $username;     //Username given on sign-up
        
    var $firstname;
        var 
    $lastname;
           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
           
    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: referrer should really only be considered the actual
        * page referrer in process.php, any other time it may be
        * inaccurate.
        */
        
        
    public function __construct(db $dbForm $form)
        {
            
    $this->database $db;
            
    $this->form $form;
            
    $this->time time();
              
    $this->startSession();
            
              
    $this->num_members = -1;
              
        }
    }
    and ive invoked it like this
    PHP Code:
    $db = new db($config);
    $user = new User($db);
    $form = new Form
    but that throws up an error
    Code:
    Catchable fatal error: Argument 2 passed to user::__construct() must be an instance of Form, none given, called in C:\wamp\www\ecornwall3\include\user.php on line 900 and defined in C:\wamp\www\ecornwall3\include\user.php on line 30
    is it possible to provide access to 2 or more classes?

    my form class is
    PHP Code:
    <?php
    /**
     * Form.php
     *
     * The Form class is meant to simplify the task of keeping
     * track of errors in user submitted forms and the form
     * field values that were entered correctly.
     *
     *  Please subscribe to our feeds at http://blog.geotitles.com for more such tutorials
     */
     
    class Form
    {
           var 
    $values = array();  //Holds submitted form field values
           
    var $errors = array();  //Holds submitted form error messages
           
    var $num_errors;   //The number of errors in submitted form

           /* Class constructor */
           
    function _construct()
        {
              
    /**
               * Get form value and error arrays, used when there
               * is an error with a user-submitted form.
               */
              
    if(isset($_SESSION['value_array']) && isset($_SESSION['error_array']))
            {
                 
    $this->values $_SESSION['value_array'];
                 
    $this->errors $_SESSION['error_array'];
                 
    $this->num_errors count($this->errors);

                 unset(
    $_SESSION['value_array']);
                 unset(
    $_SESSION['error_array']);
              }
              else
            {
                 
    $this->num_errors 0;
              }
           }

           
    /**
        * setValue - Records the value typed into the given
        * form field by the user.
        */
           
    function setValue($field$value)
        {
              
    $this->values[$field] = $value;
           }

           
    /**
        * setError - Records new form error given the form
        * field name and the error message attached to it.
        */
           
    function setError($field$errmsg)
        {
              
    $this->errors[$field] = $errmsg;
              
    $this->num_errors count($this->errors);
           }

           
    /**
        * value - Returns the value attached to the given
        * field, if none exists, the empty string is returned.
        */
           
    function value($field)
        {
              if(
    array_key_exists($field,$this->values))
            {
                 return 
    htmlspecialchars(stripslashes($this->values[$field]));
              }
            else
            {
                 return 
    "";
              }
           }

           
    /**
        * error - Returns the error message attached to the
        * given field, if none exists, the empty string is returned.
        */
           
    function error($field)
        {
              if(
    array_key_exists($field,$this->errors))
            {
                 return 
    "<font size=\"2\" color=\"#ff0000\">".$this->errors[$field]."</font>";
              }
            else
            {
                 return 
    "";
              }
           }

           
    /* getErrorArray - Returns the array of error messages */
           
    function getErrorArray()
        {
              return 
    $this->errors;
           }
    }

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

    ?>
    thanks
    Luke
    Last edited by LJackson; 10-16-2013 at 02:04 PM.

  9. #39
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Of course, but you didn't provide that information during invocation:
    PHP Code:
    $db = new db($config);
    $user = new User($db);
    $form = new Form
    User needs both objects:
    PHP Code:
    $db = new db($config);
    $form = new Form;  
    $user = new User($db$form); 
    Which is why its so useful to typehint.

    Also, you need to stop using var. It's scope is public and in a datatype weak language that's a big problem. Opt for the use of accessor and mutator methods instead (avoiding __get and __set if possible). If you use an IDE it probably has an extraction method to create the skeleton methods you require.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  10. #40
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,097
    Thanks
    297
    Thanked 12 Times in 12 Posts
    cool thanks, i didnt mention it before hand because i didnt want to over complicate things further, wanted to get one thing sorted before moving on to something else

    for some strange reason non of my form varibles seem to be being used. im not getting any php errors but when i try and enter incorrect data none of the form errors are being displayed the session values are being set ok but not the $form class properties (the form works ok if the correct data is inserted)

    if i post below the code required to submit the login form

    ok so the form itself
    PHP Code:
    include("includes/user.php");
    if($form->num_errors > 0)
            {
                   echo "<font size=\"2\" color=\"#ff0000\">".$form->num_errors." error(s) found</font>";
            }?>
            
            <form action="process.php" method="POST">
            <table align="left" border="0">
            <tr>
                <td><span>Email: <?php echo $user->form->error("user"); ?></span></td>
            </tr>
            <tr>
                <td><input type="text" name="user" maxlength="30" value="<?php echo $user->form->value("user"); ?>"></td>
            </tr>
            <tr>
                <td><span>Password: <?php echo $user->form->error("pass"); ?></span></td>
            </tr>
            <tr>
                <td><input type="password" name="pass" maxlength="30" value="<?php echo $user->form->value("pass"); ?>"></td>
            </tr>
            <tr>
                <td colspan="2" align="left"><div class="forgotpass">Forgot Your <a href="forgotpass.php">Password</a>?</div></td>
                <td align="right"></td>
            </tr>
            <tr>
                <td colspan="2" align="left"><div class="remember"><label><input type="checkbox" name="remember" <?php if($user->form->value("remember") != ""){ echo "checked"; } ?>>
                Remember me &nbsp;&nbsp;&nbsp;</label><br />(Untick this if on a public computer)</div>
                <input type="hidden" name="sublogin" value="1"></td>
            </tr>
            <tr>
                <td><input class="button orange" type="submit" value="Login"></td>
            </tr>
            </table>
            </form>
    which is submitted to process.php (ignore the global varibles, will remove them)
    PHP Code:
    <?php

    include("include/user.php");

    class 
    Process
    {
        public function 
    __construct()
        {
            global 
    $user;
            
            
    /* User submitted login form */
              
    if(isset($_POST['sublogin']))
            {
                 
    $this->procLogin();
              }
              
    /* User submitted registration form */
              
    else if(isset($_POST['subjoin']))
            {
                 
    $this->procRegister();
              }
              
    /* User submitted forgot password form */
              
    else if(isset($_POST['subforgot']))
            {
                
    $this->procForgotPass();
              }
              
    /* User submitted edit account form */
              
    else if(isset($_POST['subedit']))
            {
                 
    $this->procEditAccount();
              }
              
    /**
               * The only other reason user should be directed here
               * is if he wants to logout, which means user is
               * logged in currently.
               */
              
    else if($user->logged_in)
            {
                 
    $this->procLogout();
              }
              
    /**
               * Should not get here, which means user is viewing this page
               * by mistake and therefore is redirected.
               */
               
    else
            {
                  
    header("Location: index.php");
               }
        }
    so its $_post['sublogin'] that has been submitted which calls this $this->procLogin(); which is in the same class

    PHP Code:
           function procLogin()
        {
              global 
    $user;
            
              
    /* Login attempt */
              
    $retval $user->login($_POST['user'], $_POST['pass'], isset($_POST['remember']));
              
    /* Login successful */
              
    if($retval)
            {
                  
    $host  $_SERVER['HTTP_HOST'];
                
    $uri   rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
                
    $extra 'index.php';
                
    header("Location: http://$host$uri/$extra");
              }
              
    /* Login failed */
              
    else
            {
                 
    $_SESSION['value_array'] = $_POST;
                 
    $_SESSION['error_array'] = $user->form->getErrorArray();
                 
    header("Location: ".$user->referrer);
              }
           } 
    that calls $user->login and sets the value of $retval to 0,1 or 2 depending on the result of $user->login which is

    user.php includes
    include("include/database.php");
    include("include/mailer.php");
    include("include/form.php");

    and provides access to the db and form class in its construct method
    PHP Code:
           function login($subuser$subpass$subremember)
        {

              
    /* Username error checking */
              
    $field "user";  //Use field name for username
              
    if(!$subuser || strlen($subuser trim($subuser)) == 0)
            {
                 
    $this->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}$^";#added ^ at end!!!!!!!!!!!!!!!
                 
    if(!preg_match($regex,$subuser))
                {
                    
    $this->form->setError($field"* Email invalid");
                 }
                 
    $subuser stripslashes($subuser);
              }

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

              
    /* Checks that username is in database and password is correct */
              
    $subuser stripslashes($subuser);
              
    $result $this->confirmUserPass($subusermd5($subpass));
              
    /* Check error codes */
              
    if($result == 1)
            {
                 
    $field "user";
                 
    $this->form->setError($field"* Username not found");
              }
              else if(
    $result == 2)
            {
                 
    $field "pass";
                 
    $this->form->setError($field"* Invalid password");
              }
          
              
    /* Return if form errors exist */
              
    if($this->form->num_errors 0)
            {
                 return 
    false;
              }

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

              if(
    $subremember)
            {
                 
    setcookie("cookname"$this->usernametime()+COOKIE_EXPIRECOOKIE_PATH);
                 
    setcookie("cookid",   $this->userid,   time()+COOKIE_EXPIRECOOKIE_PATH);
              }

              
    /* Login completed successfully */
              
    return true;
           } 
    it all seems set up to work but it doesnt well not the displaying of the forms errors.

    any ideas please? thanks

    also RE: the $var's would i need to create something like this:

    so instead of $var username;

    have
    PHP Code:
    private $username;
     
        
    /**
         * @return the $username
         */
        
    public function getUsername() {
            return 
    $this->username;
        }
     
        
    /**
         * @param $newUsername
         * the name to set
         */
        
    public function setUsername($newUsername) {
            
    $this->username $newUsername
    would that be bettter? thanks mate,

    pm me your paypal address and i'll "buy you a couple of pints" for all your help!! i really appreciate it

  11. #41
    Senior Coder
    Join Date
    Jun 2008
    Location
    Cornwall
    Posts
    2,097
    Thanks
    297
    Thanked 12 Times in 12 Posts
    ok for some reason the $session_start() in the user class is either not beng started or it needs to be started sooner for the form errors to show.

    i've added session_start() to my signin.php page and everything seems to be working as expected. But im not sure why the $session_start() in the user class isnt sufficient as there was no session_start() on the original signin page.

    and your right, debugging in oop is a real paiin in the arse took me ages to figure out where the problem lay!

    right on to sorting out the $var's, would the following be a suitable replacement?
    PHP Code:
    private $username;
     
        
    /**
         * @return the $username
         */
        
    public function getUsername() {
            return 
    $this->username;
        }
     
        
    /**
         * @param $newUsername
         * the name to set
         */
        
    public function setUsername($newUsername) {
            
    $this->username $newUse
        

    instead of var $username;

    thanks


 
Page 3 of 3 FirstFirst 123

Posting Permissions

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