【发布时间】:2023-03-10 12:20:02
【问题描述】:
作为作业的一部分,我正在尝试将我的 Apache 服务器连接到 MySql 数据库。
我已验证我的 Apache 正在使用以下代码:
<?php
class RedeemAPI {
// Main method to redeem a code
function redeem() {
echo "Hello, PHP!";
}
}
// This is the first thing that gets called when this page is loaded
// Creates a new instance of the RedeemAPI class and calls the redeem method
$api = new RedeemAPI;
$api->redeem();
?>
但是当我替换此代码以从我的数据库中读取时,它给了我以下错误:
<?php
class RedeemAPI {
private $db;
// Constructor - open DB connection
function __construct() {
$this->db = new mysqli('localhost', 'username', 'password', 'promos');
$this->db->autocommit(FALSE);
}
// Destructor - close DB connection
function __destruct() {
$this->db->close();
}
// Main method to redeem a code
function redeem() {
// Print all codes in database
$stmt = $this->db->prepare('SELECT id, code, unlock_code, uses_remaining FROM rw_promo_code');
$stmt->execute();
$stmt->bind_result($id, $code, $unlock_code, $uses_remaining);
while ($stmt->fetch()) {
echo "$code has $uses_remaining uses remaining!";
}
$stmt->close();
}
}
// This is the first thing that gets called when this page is loaded
// Creates a new instance of the RedeemAPI class and calls the redeem method
$api = new RedeemAPI;
$api->redeem();
?>
错误:警告:mysqli::mysqli(): (HY000/2002): No such file or 第 8 行 /Library/WebServer/Documents/promos/index.php 中的目录
警告:mysqli::autocommit(): 无法获取 mysqli in /Library/WebServer/Documents/promos/index.php 第 9 行
警告:mysqli::prepare(): 无法获取 mysqli in /Library/WebServer/Documents/promos/index.php 第 20 行
致命错误:在非对象上调用成员函数 execute() /Library/WebServer/Documents/promos/index.php 第 21 行
请告诉我是什么原因造成的,我该如何解决。
【问题讨论】:
-
不确定为什么或如何将 Apache 连接到 MySQL,您确定您真的不想将 PHP 连接到 MySQL 吗?
-
是的,我想将 PHP 连接到 mySQL 并使用 Apache 通过本地主机请求查看我的数据库数据。这对我来说是全新的,并且正在尝试学习如何在数据库上创建 Web 服务,以便我可以进一步利用它。感谢您的回复。