Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up a database connection class in PHP

I was recently introduced to the idea of classes in PHP, and after some research I've come to the conclusion that I need to store database related functions in a class to access later. It has worked for the most part, but some use cases I am still confused with. For example,

Below is an example of how I would normally connect to my database and display information from user id's in a table

dbcon.php:

<?php
$con = mysqli_connect("host","username","password","database") or die("Couldn't connect");

require_once("functions.php");
?>

functions.php

function getUserInfo($id) {
    $query = mysqli_query($con, "SELECT * FROM users WHERE id = '$id'");
    return mysqli_fetch_array($query);
}

Some random file:

require_once("dbcon.php");

$result = mysqli_query($con, "SELECT * FROM tablename");
while ($row = mysqli_fetch_assoc($result)) {
    $userinfo = getUserInfo($row['userid']);
    echo $userinfo['name'];
}

?>

I don't feel like this method of querying the database and displaying information is the neatest or most efficient way possible. I read this article about using classes to tamper with a database and call functions that I created in the class.

My first question is this: When I try to access $con in functions.php, it is undefined. How can I pass the variable from dbcon.php to functions.php over the require_once function?

I also would like to know what the best way to store my connection to the database is, and if there are any tutorials on how to set that up.

I hope you understood that lol.

like image 307
Alex Wohlbruck Avatar asked Jan 24 '16 04:01

Alex Wohlbruck


People also ask

Can we connect to any database from PHP?

In PHP, we can connect to the database using XAMPP web server by using the following path. Steps in Detail: Open XAMPP and start running Apache, MySQL and FileZilla.


2 Answers

You can do it like this way:-

Dbconnection.php:-

<?php
Class DbConnection{
    function getdbconnect(){
        $conn = mysqli_connect("host","username","password","database") or die("Couldn't connect");
        return $conn;
    }
}
?>

Function.php:-

<?php
require_once('Dbconnection.php');
Class WorkingExamples{
    function getUserInfo($id) {
        $Dbobj = new DbConnection(); 
        $query = mysqli_query($Dbobj->getdbconnect(), "SELECT * FROM users WHERE id = '$id'");
        return mysqli_fetch_array($query);
    }
}
$data = new WorkingExamples();
echo "<pre/>";print_r($data->getUserInfo(3));
?>

Note:- this is an example, try it by changing values according to your requirement and get the result.

like image 104
Anant Kumar Singh Avatar answered Sep 21 '22 05:09

Anant Kumar Singh


<?php

class DatabaseConnection
{
    private $host       = "127.0.0.1";
    private $dbname     = "online_english";
    private $dbUsername = "root";
    private $dbPass     = "";
    private $charset    = 'utf8mb4';
    private $dsn;

    public function tryConnect(){
        try{
            $this->dsn = "mysql:host=$this->host;dbname=$this->dbname;charset=$this->charset";
            $DBH = new PDO($this->dsn,$this->dbUsername,$this->dbPass);
            $DBH->exec("set names utf8");
            $DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $DBH;
        }
        catch (PDOException $e){
            $e->getMessage();
        }
    }
}
?>
like image 44
Hello Hack Avatar answered Sep 22 '22 05:09

Hello Hack