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.
Results 1 to 14 of 14
  1. #1
    New Coder
    Join Date
    May 2009
    Posts
    59
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Using Class to connect to a database

    I have a problem using Class in PHP, this is my first time using OOP and I'm quit confused.

    this is the code :
    PHP Code:
    class db {
        private 
    $var_db_username$var_db_password$var_db_host;
        private 
    $var_db_used;
        private 
    $var_db_link;
        static public function 
    db_con($host$username$password) {
            
    $this->var_db_username $username;
            
    $this->var_db_password $password;
            
    $this->var_db_host $host;
            
    /*$this->var_db_link = */mysql_connect($this->var_db_host$this->var_db_username$this->var_db_password) or
                    die(
    "Error : "mysql_error());
        }

        static public function 
    db_select($dbname) {
            
    $this->var_db_used $dbname;
            
    mysql_select_db($this -> var_db_used$this -> var_db_link) or die("Error : "mysql_error());
        }
    }

    $obj = new db();
    $obj->db_con("localhost""root""");
    $obj->db_select("sample"); 
    The problem is, it generates this error :
    Fatal error: Using $this when not in object context in C:\xampp\htdocs\please\db.php on line 11

  • #2
    Supreme Master coder! abduraooft's Avatar
    Join Date
    Mar 2007
    Location
    N/A
    Posts
    14,852
    Thanks
    160
    Thanked 2,223 Times in 2,210 Posts
    Blog Entries
    1
    That's not the way to deal with static members of a class, refer http://php.net/manual/en/language.oop5.static.php
    The Dream is not what you see in sleep; Dream is the thing which doesn't let you sleep. --(Dr. APJ. Abdul Kalam)

  • #3
    New Coder
    Join Date
    May 2009
    Posts
    59
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thanks for that, I've got another problem..
    I got this error :
    Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'ODBC'@'localhost' (using password: NO) in C:\xampp\htdocs\please\db.php on line 12
    Error : No database selected
    Here's what the code looks like now,
    PHP Code:
    <?php
    /* 
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    class db {
        public 
    $var_db_username$var_db_password$var_db_host$var_db_used;
        public function 
    db_con($host$username$password) {
            
    $this->var_db_username $username;
            
    $this->var_db_password $password;
            
    $this->var_db_host $host;
            
    mysql_connect($this->var_db_host$this->var_db_username$this->var_db_password);
        }

        public function 
    db_select($dbname) {
            
    $this->var_db_used $dbname;
            
    mysql_select_db($dbname) or die("Error : "mysql_error());
        }

        public function 
    __destruct() { }
    }

    class 
    Signup extends db {
        
    /* for sign up */
        
    public function isUsernameAlreadyRegistered($username) {
            
    parent::db_con($this->var_db_host$this->var_db_username$this->var_db_password);
            
    parent::db_select($this->var_db_used);
            
    $sql "SELECT * FROM users WHERE username = $username";
            if ( 
    mysql_query($query) ) {
                return 
    true;
            }
            return 
    false;
        }

        public function 
    add_user($username$password$email$bday$firstname$lastname) {
            
    mysql_query("INSERT INTO users(username, password, email, birthday, firstname, lastname)
                VALUES ($username, $password, $email, $bday, $firstname, $lastname)"
    );
        }
    }
    ?>

  • #4
    Regular Coder
    Join Date
    Sep 2007
    Location
    Grahamstown, South Africa
    Posts
    237
    Thanks
    6
    Thanked 17 Times in 17 Posts
    I think the layout below is a bit easier to understand. I dont think its neccessary to mess around with static and all this fancy mumbo jumbo for now. By doing it this way it is easier to manage what you are doing! I see some weird stuff you're doing with your connection parameters, theres no need for all that assignment. Also try to do everything as simply as possible (at first) then add in the necessary complexity. (ie static, public, private, protected etc)

    PHP Code:
    <?php
    class db {
        
    //store our connection variables here
            //or we can avoid that an pass directly into function
        
    private $con_vars = array("localhost","test","test");
        public 
    $link;
        
        
    //boot strapper to make life easier for permissions
        //ie if the function is not public bootstrapper must handle
        
    public function bootStrapper($db){
            
    $this->link mysql_connect($this->con_vars[0],$this->con_vars[1],$this->con_vars[2]);
            
    $this->selectDB($db);
        }
        private function 
    selectDB($db){
            
    mysql_select_DB($db,$this->link);
        }
        private function 
    close(){
            
    mysql_close($this->link);
        }
    }
    class 
    functions extends db{
        function 
    do_something($value){
            
    //can call connect via here
            /*like this*/
    parent::bootStrapper('test');
            
    /*or like this*/$this->bootStrapper('another_test');
            print 
    $value;
        }
    }

    $test = new functions;
    //or externally
    //$test->bootStrapper('test');
    $test->do_something('Hello World');
    ?>
    Remember that at any time during the execution of this program you will be connected to the database! you only need to close the con once you have run the functions you need:
    ie:
    1.) run boot strapper (connected to the db)
    2.) run addUser (still connected) -> this function is stored in the functions (or whatever you want to call it)
    3.) run $test->close() (not connected anymore)
    Last edited by idalatob; 11-22-2010 at 01:12 PM.

  • #5
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,253
    Thanks
    12
    Thanked 341 Times in 337 Posts
    you can have a look at PHP’s database classes (PDO, MySQLi). there is really no need to combine mysql_* functions with OOP.

    @idalatob: $test->close() is a candidate for __destruct()
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #6
    New Coder
    Join Date
    May 2009
    Posts
    59
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Can you help me out with this one? It doesn't produce any error but can't add a data on my database.

    Here's the class I'm using :
    PHP Code:
    <?php
    class Database {
        public 
    $dbhost$dbusername$dbpassword$dbused$dblink;
        function 
    __construct() {
            
    $this->dbhost "localhost";
            
    $this->dbusername "root";
            
    $this->dbpassword "";
        }

        function 
    connectTo($dbused) {
            
    $this->dbused $dbused;
            
    $this->dblink mysql_connect($this->dbhost$this->dbusername$this->dbpassword) or die("Error : "mysql_error());
        }

        function 
    addUser($entry = array()) {
            
    $this->connectTo($this->dbused);
            if ( !
    $this->dblink ) {
                die(
    "Could not connect : "mysql_error());
            }
            
    mysql_select_db($this->dbused);
            
    $sql "INSERT INTO users(username, password, email, birthday, firstname, lastname) VALUES(";
            foreach ( 
    $entry as $i => $value ) {
                
    $sql .= "$value,";
            }
            
    $sql .= ")";
            
    mysql_query($sql);
        }

        function  
    __destruct() {
            
    mysql_close($this->dblink);
        }
    }
    ?>
    and this one is on my some .php file
    PHP Code:
    <?php
    require 'db.php';
    $Database = new Database();
    $toReg = array(
        
    => $_POST["s_username"],
        
    => sha1($_POST["s_password"]),
        
    => $_POST["s_email"],
        
    => $_POST["s_firstname"],
        
    => $_POST["s_lastname"],
        
    => $_POST["s_birthday"]
    );
        if ( isset(
    $toReg[0]) ) {
            
    $Database->connectTo("ufaceoff");
            
    $Database->addUser($toReg);
        }

    ?>

  • #7
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,253
    Thanks
    12
    Thanked 341 Times in 337 Posts
    I bet there is an SQL error (you don’t test whether mysql_query() succeeds). I’d go for a comma too much.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #8
    New Coder
    Join Date
    May 2009
    Posts
    59
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Updated codes, still it didn't work..

    PHP Code:
    <?php
    class Database {
        public 
    $dbhost$dbusername$dbpassword$dbused$dblink;
        function 
    __construct() {
            
    $this->dbhost "localhost";
            
    $this->dbusername "root";
            
    $this->dbpassword "";
        }

        function 
    connectTo($dbused) {
            
    $this->dbused $dbused;
            
    $this->dblink mysql_connect($this->dbhost$this->dbusername$this->dbpassword) or die("Error : "mysql_error());
        }

        function 
    addUser($entry = array()) {
            
    $this->connectTo($this->dbused);
            if ( !
    $this->dblink ) {
                die(
    "Could not connect : "mysql_error());
            }
            
    mysql_select_db($this->dbused);
            
    $sql "INSERT INTO users(username, password, email, birthday, firstname, lastname) VALUES(";
            foreach ( 
    $entry as $i => $value ) {
                if ( 
    $i sizeof($entry) ) {
                    
    $sql .= $value .", ";
                } else {
                    
    $sql .= $value;
                }
            }
            
    $sql .= ")";
            
    mysql_query($sql);
        }

        function  
    __destruct() {
            
    mysql_close($this->dblink);
        }
    }
    ?>

  • #9
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,253
    Thanks
    12
    Thanked 341 Times in 337 Posts
    what does mysql_query() return?

    Edit: you are aware that string input must be quoted in SQL? (Prepared Statements being the exception here)
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #10
    New Coder
    Join Date
    May 2009
    Posts
    59
    Thanks
    1
    Thanked 0 Times in 0 Posts
    It return nothing.. the page still remains the same.
    PHP Code:
            foreach ( $entry as $i => $value ) {
                if ( 
    $i sizeof($entry) ) {
                    
    $sql .= mysql_real_escape_string($entry[$i]) .", ";
                } else {
                    
    $sql .= mysql_real_escape_string($entry[$i]);
                }
                echo 
    mysql_real_escape_string($entry[$i]) ."\n";
            } 
    I tried echoing and see if the function reads the array $entry, it prints though.. the problem might be on teh SQL. :/

  • #11
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,253
    Thanks
    12
    Thanked 341 Times in 337 Posts
    as I (and many others) said: mysql_query($sql) or die(mysql_error());
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #12
    New Coder
    Join Date
    May 2009
    Posts
    59
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Error : Column count doesn't match value count at row 1
    row 1 is for the password, and I used sha1() to encrypt it and store it as VARCHAR on my database.



    ------------

    Edited :
    Should I convert the password to SHA1 on PHP or in SQL?
    Last edited by flint0131; 11-24-2010 at 02:48 PM.

  • #13
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,253
    Thanks
    12
    Thanked 341 Times in 337 Posts
    does the varchar has the right size? (SHA1 usually requires exactly 40 characters)

    you can hash it on either side. should you want to use secure hash algorithms (SHA256, RIPEMD160, etc.), you need to use PHP.
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer

  • #14
    New Coder
    Join Date
    May 2009
    Posts
    59
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thanks.. got my code working. ^_^


  •  

    Posting Permissions

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