提问人:Scorekaj22 提问时间:4/26/2017 最后编辑:CommunityScorekaj22 更新时间:12/10/2020 访问量:1832
在PHP中使用另一个类中的MySQLi
Using MySQLi from another class in PHP
问:
我真的希望有人能帮我弄清楚我错过了什么。我已将安装从 PHP 5.6 升级到 7.0,这迫使我从 Mysql 更新到 Mysqli,由于某种原因,这破坏了我的设置。
我研究并遵循了本指南“在其他类中使用 MySQLi”:在其他类中使用 MySQLi
我是作为最后的手段写作的,并且也查看了其他网站,但问题似乎来自其他地方。
首先,我有一个数据库类:
private $serverName = "localhost";
private $userName = "DBUserName";
private $pass = "UserPassword";
private $database = "SelectedDB";
public $conn;
public function __construct(){
$this->conn = new mysqli($this->serverName, $this->userName,$this->pass,$this->database);
}
然后我有一个 API 类,我想在其中访问这个连接,它看起来像
require_once 'Database.php';
class MyAPI{
private $db;
public function __construct($request_uri, $postData, $origin) {
$this->db = new Database();
}
最后,我尝试从一个函数调用它:
$getUserResult = mysqli_query( $this->db->conn, $getUserQry);
每当我调用 $this->db->conn 时,我都会收到内部服务器错误 500
如果我在 MyAPI 类中创建数据库连接,则不会出现任何问题,这对我来说似乎很奇怪。
我希望有人能给我指一个方向。
更新: 我更正了脚本中的拼写错误,现在我得到 200,但查询mysqli_query中的值仍然为 null。
如果我创建 $dbtest = new database();并使用它来代替它工作正常。有没有办法让它在构造函数中工作,并引用$db?
答:
1赞
Your Common Sense
4/26/2017
#1
有几个不良做法导致您出现此错误。
显然,从数据库扩展 User 是一个错误的举动。此外,整个 Database 类相当无用,因为它不做任何有用的事情。
因此,我建议
- 摆脱无用的 Database 类。
- 从 vanilla mysqli 创建单个 $db 实例。
- 将其作为构造函数参数传递到需要数据库连接的每个类中
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']);
评论
error.log
private $db;
应该在类定义中error_reporting(E_ALL); ini_set('display_errors', 1);