Create a database connection using OOP PHP [with example and explanation ] 2022

    By: Thad Mertz
    1 year ago

    Ok so create a class called DB or any other name you prefer, DB for basically database so that you know why you created this class.

    <?php
    
    namespace services;
    
    use mysqli;
    
    class DB
    {
        public $db_host = 'localhost';
        public $db_user = 'root';
        public $db_password = 'awesomemanu';
        public $db_database = 'react_php';
    
    
    
        public function database()
        {
            $conn = new mysqli($this->db_host, $this->db_user, $this->db_password, $this->db_database);
    
    
            // Check connection
            if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
            }
    
            //echo "Connected successfully";
            return $conn;
        }
    }
    

    Here you can see we have a connection now in any php file when ever you want to use this connection call it like this

    <?php
    
    
    namespace Api\Controllers;
    
    
    use Services\DB;
    
    
    class PostsController
    {
        public $conn = null;
    
    
    
        public function __construct()
        {
            // Create connection
            $this->conn = (new DB())->database();
        
        }
    


    Now $this-conn has the database.

    Use in your queries

        public function savePostsToDatabase($posts)
        {        
            
            // Check connection
            if ($this->conn->connect_error) {
                die("Connection failed: " . $this->conn->connect_error);
            }
    
    
            $sql = "INSERT INTO posts (firstname, lastname, email)
            VALUES ('John', 'Doe', 'john@example.com')";
    
    
    
            if (mysqli_query($this->conn, $sql)) {                      // Here we used it.
                echo "New record created successfully";
            } else {
                echo "Error: " . $sql . "<br>" . mysqli_error($this->conn);
            }
            
            mysqli_close($this->conn);
    
    
        }
    

    Hope this helps