Using MySQLi from another class in PHP

There are several bad practices that led you to this error.

Clearly, extending User from a Database is a wrong move. Also, the whole Database class is rather useless as it doesn’t do anything useful.

Hence I would suggest to

  • get rid of the useless Database class.
  • create a single $db instance from vanilla mysqli.
  • pass it as a constructor parameter into every class that needs a database connection

database.php:

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli("localhost", "DBUserName", "UserPassword", "SelectedDB");
$db->set_charset('utf8mb4');

myapi.php

<?php
class MyAPI
{
    protected $db;

    public function __construct($db, $request_uri, $postData, $origin)
    {
        $this->db = $db;
    }

    public function getUser($id)
    {
        $sql = "SELECT * FROM users where id=?";
        $stmt = $this->db->prepate($sql);
        $stmt->bind_param("s", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        return $result->fetch_assoc();
    }
}

app.php

<?php
# require_once 'Database.php';
# require_once 'myapi.php';
require 'vendor/autoload.php'; // autoloading is a must

$api = new MyAPI($db, $request_uri, $postData, $origin);
$user = $api->getUser($_POST['id']);

Leave a Comment