dcsimg
www.webdeveloper.com
Results 1 to 4 of 4

Thread: [RESOLVED] How to connect to db using one class and use this connection in another class?

  1. #1
    Join Date
    Mar 2017
    Posts
    7

    resolved [RESOLVED] How to connect to db using one class and use this connection in another class?

    I want to use one class to connect to a database and then access this connection from another class that is responsible for creating, reading, updating and deleting data.

    The first class is defined as follows:

    PHP Code:
    class Database
    {
        private 
    $host="localhost";
        private 
    $user="sandmannz123";
        private 
    $db="friends";
        private 
    $pass="passworda";
        
    /** TRUE if static variables have been initialized. FALSE otherwise
        */
        
    private static $init FALSE;
        
    /** The mysqli connection object
        */
        
    public static $conn;
        
    /** initializes the static class variables. Only runs initialization once.
        * does not return anything.
        */
        
    public static function initialize()
        {
            if (
    self::$init===TRUE)return;
            
    self::$init TRUE;
            
    //self::$conn = new PDO("mysql:host=".$this->host.";dbname=".$this->db,$this->user,$this->pass);
            
    self::$conn = new mysqli("localhost""sandmannz123""passworda""friends");
        }

    The following is part of another class that attempts to use the connection created from the Database class:

    PHP Code:
    class oopCrud{

        public function 
    registernewuser($username,$email,$password,$avatar,$table){
            try{
        
            
    $sql "INSERT INTO $table SET username=:username,email=:email,password=:password,avatar=:avatar";
                
    //$sql = "INSERT INTO users SET username=:username,email=:email,password=:password"; 
            
    $q Database::$conn->prepare($sql);
            
    $q->execute(array('username'=>$username,'email'=>$email,'password'=>$password,'avatar'=>$avatar));
            return 
    true;    
            }
            catch (
    PDOException $e)
            {
                print(
    'Unable to register user.');
                exit();
            }
            
        }
    public function 
    test_input($data){
            
    $data htmlspecialchars($data);
            
    $data trim($data);
            
    $data stripslashes($data);
            return 
    $data;
        } 
    The above classes are used on a page called form.php as follows:

    PHP Code:
    session_start();
    $_SESSION['message'] = '';
      
    spl_autoload_register(function ($class) {
        include_once(
    'oopCRUD.php');
        });
        
        
    Database::initialize();
          
    $obj=new oopCrud;

    if(isset(
    $_POST['register'])){
        
    //Two passwords match
        
    if($_POST['password'] == $_POST['confirmpassword']){
            
    $username $obj->test_input($_POST['username']);
            
    $email $obj->test_input($_POST['email']);
            
    $password $obj->test_input($_POST['password']);
            
    $avatar_path 'images/'.$_FILES['avatar']['name'];
            
            
    //make sure file type is image
            
    if(preg_match("!image!"$_FILES['avatar']['type'])) {
                
    //copy image to images folder
                
    if(copy($_FILES['avatar']['tmp_name'],$avatar_path)){
                    
    $_SESSION['username']=$username;
                    
    $_SESSION['avatar']=$avatar_path;
                    
    $obj->registernewuser($username,$email,$password,$avatar_path,"users");
                }
            }
        }
            exit();
        } 
    When running the above code I am getting:
    "Fatal error: Call to a member function execute() on a non-object in C:\wamp\www\friends\oopCRUD.php on line 68"

    Any help greatly appreciated.

    Please be aware I'm new to coding with OOP based php.

    Related question: I would like to use a PDO way of connecting to the database rather than self::$conn = new mysqli("localhost", "sandmannz123", "passworda", "friends");
    How would I do that?
    I have commented out an attempt I made in the Database class as follows:
    //self::$conn = new PDO("mysql:host=".$this->host.";dbname=".$this->db,$this->user,$this->pass);

  2. #2
    Join Date
    Mar 2017
    Posts
    7

    Problem Solved

    Managed to fix this myself. Probloem was with the PDO and mysqli mix and also changed the $host, $user, $db and $pass variables to private static. Database class now reads as follows:

    PHP Code:
    class Database
    {
        private static 
    $host="localhost";
        private static 
    $user="sandmannz123";
        private static 
    $db="friends";
        private static 
    $pass="passworda";
        
    /** TRUE if static variables have been initialized. FALSE otherwise
        */
        
    private static $init FALSE;
        
    /** The mysqli connection object
        */
        
    public static $conn;
        
    /** initializes the static class variables. Only runs initialization once.
        * does not return anything.
        */
        
    public static function initialize()
        {
            if (
    self::$init===TRUE)return;
            
    self::$init TRUE;
            
    self::$conn = new PDO("mysql:host=".self::$host.";dbname=".self::$db,self::$user,self::$pass);
        }


  3. #3
    Join Date
    Jul 2013
    Location
    Voorheesville NY USA
    Posts
    1,766
    Include $conn as an argument to your 'other-class' functions?
    JG
    PS - If you're posting here you should be using:

    error_reporting(E_ALL);
    ini_set('display_errors', '1');


    at the top of ALL php code while you develop it!

  4. #4
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    21,979
    We could get into a long discussion/debate about whether or not to use a Singleton DB class, whether the DB class should be passed to the constructors of classes that need it or instantiated within those classes or stored in a separate configuration class that gets passed in, etc. But if you have it working now, this is probably not the place to do it.
    "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

Thread Information

Users Browsing this Thread

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

Tags for this Thread

Posting Permissions

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



Recent Articles