Database query oop
Results 1 to 13 of 13

Thread: Database query oop

  1. #1
    Senior Member cluelessPHP's Avatar
    Join Date
    Apr 2015
    Location
    Scotland
    Posts
    345

    Database query oop

    So I was looking over this:
    http://stackoverflow.com/questions/1.../php-construct

    I thought ok, I get it so I went to try it myself

    PHP Code:
    <?php

    require "loadclasses.php";
    class 
    Login
    {
        
        private 
            
    $email,
            
    $password,
            
    $database;
        
        private static
        
    $emptyInput 0,
        
    $emaillogin;
        
        
        public function 
    __construct() 
        {
            
    $this->database = new Database();
        }
        
        public static function 
    validateEmptyEmail($email)
        {
            return(
    strlen($email)) > self::$emptyInput;
        }
        public static function 
    validateEmptyPassword($password)
        {
            return(
    strlen($password)) > self::$emptyInput;
        }
        
        public static function 
    checkActive($email)
        {
            
    $database->query('select eMail,active from username WHERE eMail = :emaillogin  AND active = 0');
            
    $database->execute();
            
    $database->rowCount();    
        
            
    $database->rowCount();
            if (
    $database->rowCount() === 1)
            {
                return 
    $emaillogin;
            }                 
        }
            
    }
    PHP Code:
    <?php
    date_default_timezone_set
    ("Europe/London");


    error_reporting(-1); // reports all errors
    ini_set("display_errors""1"); // shows all errors
    ini_set("log_errors"1);
    ini_set("error_log""php-error.log");

    class 
    Database
    {
        private 
    $host "localhost";
        private 
    $user "root";
        private 
    $pass "";
        private 
    $dbname "got";
        
        private 
    $dbh;
        private 
    $error;
        private 
    $stmt;
        
        public function 
    __construct()
        {
            
    //SET DSN
            
    $dsn "mysql:host="$this->host ";dbname=" $this->dbname;
            
            
    $options = array
            (
                
    PDO::ATTR_PERSISTENT     => true,
                
    PDO::ATTR_ERRMODE         =>PDO::ERRMODE_EXCEPTION
            
    );
        
    //create PDO
        
    try
        {
            
    $this->dbh = new PDO($dsn$this->user$this->pass$options);
        }
        catch(
    PDOEception $e)
        {
            
    $this->error $e->getMessage();
        }
        }
        
        public function 
    query($query)
        {
            
    $this->stmt $this->dbh->prepare($query);
        }
        
        public function 
    bind($param$value$type null)
        {
            if(
    is_null($type))
            {
                switch(
    true)
                {
                    case 
    is_int($value):
                    
    $type PDO::PARAM_INT;
                    break;
                    case 
    is_bool($value):
                    
    $type PDO::PARAM_BOOL;
                    break;
                    case 
    is_null($value):
                    
    $type PDO::PARAM_NULL;
                    break;
                    default:
                    
    $type PDO::PARAM_STR;
                }
            }
            
            
    $this->stmt->bindValue($param$value$type);
        }
        
        public function 
    execute()
        {
            return 
    $this->stmt->execute();
        }
        
        public function 
    lastInsertId()
        {
            
    $this->dbh->lastInsertId();
        }
        public function 
    rowCount()
        {
            
    $this->stmt->rowCount();
        }
        
        public function 
    connect()
        {
            
    $this->dbh->connect();
        }
        
        public function 
    resultset()
        {
            
    $this->execute();
            return 
    $this->stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    }
    PHP Code:
    <?php 

    error_reporting
    (-1); // reports all errors    
    ini_set("display_errors""1"); // shows all errors    
    ini_set("log_errors"1);    
    ini_set("error_log""register.log");  
    require 
    "loadclasses.php";
    $database = new Login;

    session_start();


        
    $post filter_input_array(INPUT_POSTFILTER_SANITIZE_STRING);        
        
        
    $emaillogin $passwordlogin "";
        
    $emaillogin $post["emaillogin"];
        
    $passwordlogin $post["passwordlogin"];
        
        
            
    $errors = array();
    $fields = array( 
      
    'emaillogin' => array( 
        
    'validator' => 'validateEmptyEmail'
        
    'message'   => 'Email is required'
      ), 
      
    'passwordlogin' => array( 
        
    'validator' => 'validateEmptyPassword'
        
    'message'   => 'Password is required' 
      
    ),
      
    'passwordlogin' => array( 
        
    'validator' => 'checkActive'
        
    'message'   => ' is required' 
      
    )
    );  
            
        foreach(
    $post as $key => $value
        {
            if(isset(
    $fields[$key])) 
            {
                if(!
    Login::{$fields[$key]['validator']}($value)) 
                {
                    
    $errors[] = ['name' => $key'error' => $fields[$key]['message']];
                }
            }
        }

    header('Content-Type: application/json');
    if (empty(
    $errors))
    {
        
    //echo json_encode($success);
    }
    else
    {
        echo 
    json_encode(["errors" => $errors]);
    }

    Error message
    Code:
    <br />
    <b>Notice</b>:  Undefined variable: database in <b>E:\EasyPHP-Devserver-16.1\eds-www\gotsocial\classes\Login.class.php</b> on line <b>33</b><br />
    <br />
    <b>Fatal error</b>:  Uncaught Error: Call to a member function query() on unknown in E:\EasyPHP-Devserver-16.1\eds-www\gotsocial\classes\Login.class.php:33
    Stack trace:
    #0 E:\EasyPHP-Devserver-16.1\eds-www\gotsocial\loginForm.php(40): Login::checkActive('kkkkkkk')
    #1 {main}
      thrown in <b>E:\EasyPHP-Devserver-16.1\eds-www\gotsocial\classes\Login.class.php</b> on line <b>33</b><br />
    You need to believe in things that aren't true. How else can they become?― Terry Pratchett, Hogfather
    Blog

    Six month project

  2. #2
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    14,725
    Noticed that in the first code snippet, you should reference $this->database->query() and such in the checkActive() method.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  3. #3
    Senior Member cluelessPHP's Avatar
    Join Date
    Apr 2015
    Location
    Scotland
    Posts
    345
    PHP Code:
     public static function checkActive($email
        { 
            
    $this->database->query('select eMail,active from username WHERE eMail = :emaillogin  AND active = 0'); 
            
    $this->database->execute(); 
            
    $this->database->rowCount();     
         
            
    $database->rowCount(); 
            if (
    $database->rowCount() === 1
            { 
                return 
    $emaillogin
            }                  
        } 
    Is that I attempted at one point not long ago i

    Code:
    <br />
    <b>Fatal error</b>:  Uncaught Error: Using $this when not in object context in E:\EasyPHP-Devserver-16.1\eds-www\gotsocial\classes\Login.class.php:33
    Stack trace:
    #0 E:\EasyPHP-Devserver-16.1\eds-www\gotsocial\loginForm.php(40): Login::checkActive('hjkhjkhjk')
    #1 {main}
      thrown in <b>E:\EasyPHP-Devserver-16.1\eds-www\gotsocial\classes\Login.class.php</b> on line <b>33</b><br />
    You need to believe in things that aren't true. How else can they become?― Terry Pratchett, Hogfather
    Blog

    Six month project

  4. #4
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    14,725
    Unless you have a specific reason to be using static methods in that class, I would get rid of the "static" part of their declarations. If you do have a reason for them to be static, then we need to rethink things, as those methods currently depend on the constructor being called and initializing your DB connection -- but static methods can be called without ever instantiating the class as an object (which is when __construct() gets run).
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  5. #5
    Senior Member cluelessPHP's Avatar
    Join Date
    Apr 2015
    Location
    Scotland
    Posts
    345
    Quote Originally Posted by NogDog View Post
    Unless you have a specific reason to be using static methods in that class, I would get rid of the "static" part of their declarations. If you do have a reason for them to be static, then we need to rethink things, as those methods currently depend on the constructor being called and initializing your DB connection -- but static methods can be called without ever instantiating the class as an object (which is when __construct() gets run).
    Main reason was...I started stabbing in the dark, oh and I wasn't entirely sure about making a controller outside of static (I have been using your template)

    I'm guessing I could just as easily do something akin to this?
    PHP Code:
     private  
            
    $email
            
    $password
            
    $database
            
    $emptyInput 0
            
    $emaillogin
    You need to believe in things that aren't true. How else can they become?― Terry Pratchett, Hogfather
    Blog

    Six month project

  6. #6
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    14,725
    If you want to stick with using static methods, then you might want to make one of the params for that method to be your database object. That way you would pass it in as a dependency just in that case, as opposed to making it something the class has to create.
    PHP Code:
        public static function checkActive($emailPDO $database)
        {
            
    $stmt $database->prepare('select eMail, active from username WHERE eMail = :emaillogin  AND active = 0');
            
    $stmt->execute(array(':emaillogin' => $email)); // need to bind your variable to the place-holder
            
    return $stmt->fetch(PDO::FETCH_ASSOC); // returns FALSE if no match
        

    In that case, you would no longer need/want a __construct() method.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  7. #7
    Senior Member cluelessPHP's Avatar
    Join Date
    Apr 2015
    Location
    Scotland
    Posts
    345
    Ideally I want to be responsible for my own code, I'm relying on you guys too heavily at the moment I think. The main problem I "think" I have is interaction with what I write, if that makes sense? And when to use static/non static methods, tomorrow I'll try and get to grips with interacting with controls more ermmm.. fluidly?
    You need to believe in things that aren't true. How else can they become?― Terry Pratchett, Hogfather
    Blog

    Six month project

  8. #8
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    14,725
    In terms of learning OOP, this may have been a less than ideal path, in that we started out by using a class as a way to store a bunch of related but stand-alone validation functions -- but we weren't really modelling an object (and thus never actually instantiating one).

    From an OOP point of view, it might make more sense to think of a User class with the properties that define a user, and which might then include a method that validates if an email address is okay?
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  9. #9
    Senior Member cluelessPHP's Avatar
    Join Date
    Apr 2015
    Location
    Scotland
    Posts
    345
    You mean like in the accepted answer on here?

    http://stackoverflow.com/questions/4...-logout-signup
    You need to believe in things that aren't true. How else can they become?― Terry Pratchett, Hogfather
    Blog

    Six month project

  10. #10
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    14,725
    Without looking at it in detail, that seems the general idea. The class is a noun that represents some thing (even if it's a concept), and its methods are the verbs that either act on that object or generate results based on that object.
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  11. #11
    Senior Member
    Join Date
    Apr 2003
    Location
    Flanders Fields
    Posts
    5,824
    I was an OOP late bloomer in many respects. I'd like to volunteer some thoughts on static properties and methods:
    * think of static methods & properties as definining a single function or variable -- there's only ONE regardless of how many instances of your class may exist. While each instance of a class has its own personal variant of each non-static properties, all of those instances share collectively the static properties.
    * static functions cannot refer to $this. This causes a error:
    PHP Code:
    class Foo {
            public 
    $bar
            public static function 
    func() {
                    echo 
    $this->bar;
            }
    }

    Foo::func(); // PHP Fatal error:  Using $this when not in object context in /tmp/foo.php on line 6 
    * any function that doesn't need to refer to the 'internal' properties of a particular object can be defined as static
    * it is sometimes helpful for code organization to define static methods which capture some operation intrinsically associated with that object.
    * static methods and properties can be called/accessed without creating an instance of the class
    * non-static methods and properties can only be referenced when you've created an instance of your class.

    You may find this example useful:
    PHP Code:
    class Circle {
            private 
    $radius;


            public function 
    __construct($r) {
                    
    $this->radius $r;
            }

            
    // applies to all circles, can be used without instantiating this class
            
    public static function calculate_area($radius) {
                    return 
    pow($radius2) * M_PI;
            }

            
    // method of this class, can be used on any give instance
            
    public function area() {
                    return 
    self::calculate_area($this->radius);
            }
    }

    $circ = new Circle(2);
    echo 
    "my circle's area is " $circ->area() . "\n";


    echo 
    "a circle with radius 3 has an area of " Circle::calculate_area(3) . "\n"
    IMPORTANT: STOP using the mysql extension. Use mysqli or pdo instead.
    World War One happened 100 years ago. Visit Old Grey Horror for the agony and irony.

  12. #12
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    14,725
    NogDog's rules of OOPHP adjectives:

    - If unsure, make it private -- you can always open up access later.
    - If unsure, do not make it static -- you can always change it later.

    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  13. #13
    Senior Member cluelessPHP's Avatar
    Join Date
    Apr 2015
    Location
    Scotland
    Posts
    345
    Quote Originally Posted by sneakyimp View Post
    I was an OOP late bloomer in many respects. I'd like to volunteer some thoughts on static properties and methods:
    * think of static methods & properties as definining a single function or variable -- there's only ONE regardless of how many instances of your class may exist. While each instance of a class has its own personal variant of each non-static properties, all of those instances share collectively the static properties.
    * static functions cannot refer to $this. This causes a error:
    PHP Code:
    class Foo {
            public 
    $bar
            public static function 
    func() {
                    echo 
    $this->bar;
            }
    }

    Foo::func(); // PHP Fatal error:  Using $this when not in object context in /tmp/foo.php on line 6 
    * any function that doesn't need to refer to the 'internal' properties of a particular object can be defined as static
    * it is sometimes helpful for code organization to define static methods which capture some operation intrinsically associated with that object.
    * static methods and properties can be called/accessed without creating an instance of the class
    * non-static methods and properties can only be referenced when you've created an instance of your class.

    You may find this example useful:
    PHP Code:
    class Circle {
            private 
    $radius;


            public function 
    __construct($r) {
                    
    $this->radius $r;
            }

            
    // applies to all circles, can be used without instantiating this class
            
    public static function calculate_area($radius) {
                    return 
    pow($radius2) * M_PI;
            }

            
    // method of this class, can be used on any give instance
            
    public function area() {
                    return 
    self::calculate_area($this->radius);
            }
    }

    $circ = new Circle(2);
    echo 
    "my circle's area is " $circ->area() . "\n";


    echo 
    "a circle with radius 3 has an area of " Circle::calculate_area(3) . "\n"
    That's great, will sit and play around with it tonight
    You need to believe in things that aren't true. How else can they become?― Terry Pratchett, Hogfather
    Blog

    Six month project

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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