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.

Answer

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.

Leave a Reply

Your email address will not be published. Required fields are marked *