Using MySQLi from another class in PHP

后端 未结 1 1823
你的背包
你的背包 2020-12-11 10:49

I really hope someone can help me figure out what I am missing. I have upgraded my installation from PHP 5.6 to 7.0 and this has forced me to update from Mysql to Mysqli whi

相关标签:
1条回答
  • 2020-12-11 11:31

    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']);
    
    0 讨论(0)
提交回复
热议问题