0

So, I'm in the middle of writing a web application for one of my clients, and I've decided to keep the database connection in a class. The following code is what I have:

class databaseConnection {
    private $hostname = 'hn.app.dev';
    private $username = 'root';
    private $password = '';
    private $database = 'hn_app_dev';
    public function connect() {
        $host = mysqli_connect($this->hostname, $this->username, $this->password);
        if ($host) {
            $connection = mysqli_select_db($host, $this->database);
            if (!$connection) {
                die('An error occured while trying to connect to the database.');
            }
            return $connection;
        }
    }
}

I am using the standard PHP function of mysqli_query to send queries to the database. I am using the following to send queries to the database:

function fetch_from_db($query) {
    $connection = new databaseConnection();
    $query = mysqli_query($connection->$connection, 'QUERY');
}

I'm new to using classes in my code. I'm still learning, as we all are. I've checked about but cannot find a fix for my issue. I know what the issue is: it's an issue with the class being an object, and something to do with fetching the returned $connection variable from it.

How can I fix this issue so that I can connect correctly to my database? Also, could anyone point me in the direction of some documentation that I could learn the fix so I can tackle this in future.

Thank you!

3
  • $connection->connect() Commented Jan 23, 2016 at 20:51
  • @Federico he's using mysqli functions, not mysql Commented Jan 23, 2016 at 20:55
  • my bad, I've read wrong Commented Jan 23, 2016 at 20:55

3 Answers 3

2

There are a lot of different ways you could write a object to handle connections and queries to the database.

What matters most is what your trying to achieve.

I would think these would be a few features you would like to have.

  • Single Connection
  • Runs SQL and returns mysqli results.
  • Access to the connection for escaping values.
  • It looks like you want to store your credentials within the object it self. ( I would suggest passing these in as a value in __construct()

These are a few basic features, that could easily be expanded apon.

 class databaseConnection {
    //private $hostname = 'hn.app.dev';
    //private $username = 'root';
    //private $password = '';
    //private $database = 'hn_app_dev';

    private $connection; // this is where the object will store the connection for other methods to access it
    
    public function __construct($host, $username, $password, $database)
    //public function connect() {
        $this->connection = mysqli_connect($host, $username, $password);
        if ($host) {
            $this->connection->select_db($database); 
            if (!$this->connection) {
                die('An error occured while trying to connect to the database.');
            }
            return $connection;
        }
    }

    // this is so databaseConnection $db can access the connection for escaping MySQLi SQL
    public function connection(){
         return $this->connection;
    }

    function fetch_from_db($query) {
        //$connection = new databaseConnection(); // I don't believe you really want to create a instance of this object inside of itself
        //$query = mysqli_query($connection->$connection, 'QUERY');
        $query = $this->connection->query($query); // we will use the object oriented style instead of the above procedural line
        return $query; // return the results to the $results var in the bottom example
    }

    // this is a magic function that is called when the object is destroyed, so we will close the connection to avoid to many connections
    function __destruct(){
      $this->connection()->close();
    }
}


// make a new datbaseConnection class with specific credentials
$db = new databaseConnection('localhost', 'someuser', 'somepass', 'somedb');
$sql = 'SELECT * FROM tableName LIMIT 100';

// call the fetch_from_db function from the new databaseConnection $db
$results = $db->fetch_from_db($sql);

// print the results
while($result = $results->fetch_assoc()){
  print_r($result); // print_r on each row selected from db
}

You can learn more about OOP and PHP Objects in the Manual and there are many tutorials available online about specifically classes to manage database connections and queries.

Hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Very nice and thought out answer. +1
1

If you're going to keep it in a class, you never call the connect() function. But if you want it connected when you initiate the class, change the connect() function to __construct() and remove the return and assign it to a public variable.

class databaseConnection {
    private $hostname = 'hn.app.dev';
    private $username = 'root';
    private $password = '';
    private $database = 'hn_app_dev';
    public $connection;
    public function __construct() {
        $host = mysqli_connect($this->hostname, $this->username, $this->password);
        if ($host) {
            $connection = mysqli_select_db($host, $this->database);
            if (!$connection) {
                die('An error occured while trying to connect to the database.');
            }
            $this->connection = $host;
        }
    }
}

After that, you can get the database connection in your function like:

function fetch_from_db($query) {
    $connection = new databaseConnection();
    $query = mysqli_query($connection->connection, 'QUERY');
}

Now, after having said all that, you don't want to create a new instance in every function to access the database. So possibly making it static and create an init() function of sorts so it takes less memory in the overall application.

For class documentation PHP's Classes/Objects page will help. Specifically the 'Examples' link.

2 Comments

I am getting a boolean response from this which is '1', rather than the connection itself. Any idea why? Thanks.
Oh, boolean because mysql_select_db returns true or false, but still works on the original connection. Updated code example.
0
<?php

class databaseConnection {
    private $hostname = 'localhost';
    private $username = 'root';
    private $password = '';
    private $database = 'onlinylh_sggsfaculty';
    public function connect() {
        $host = mysqli_connect($this->hostname, $this->username, $this->password,$this->database);
        if ($host) {
            return $host;
        }
        else{
            echo "Error";
        }
    }
}
function fetch_from_db($query) {
    $conn = new databaseConnection();
    $r = mysqli_query($conn->connect(), $query);
}
fetch_from_db()
?>

This Worked For me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.