Using MySQLi from another class in PHP

后端 未结 1 1828
你的背包
你的背包 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:

    set_charset('utf8mb4');
    

    myapi.php

    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

    getUser($_POST['id']);
    

    0 讨论(0)
提交回复
热议问题