【问题标题】:Connecting apachec to mysql data base将apache连接到mysql数据库
【发布时间】: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 行

请告诉我是什么原因造成的,我该如何解决。

【问题讨论】:

标签: php mysql mysqli


【解决方案1】:

要连接php到mysql,你需要放置以下代码来检查连接是否完成 -

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

让我知道现在会发生什么错误?

【讨论】:

  • 这里是错误:警告:mysqli::mysqli(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES) in /Library/WebServer第 7 行的 /Documents/promos/index.php 连接失败:用户 'username'@'localhost' 的访问被拒绝(使用密码:YES)
  • @ddesai 您的用户名或密码似乎不正确。你检查过这些吗?您是否在 MySQL 实例上设置了 MySQL 用户?
  • @ddesai,是的,您的用户名或密码不正确。
  • 所以我从系统首选项重新启动了我的 sql 服务器并尝试从命令行登录到我的服务器,它给了我以下错误:错误 2002 (HY000): 无法通过套接字连接到本地 MySQL 服务器'/tmp/mysql.sock' (2)。我认为我的 SQL 服务器搞砸了。我想我应该尝试重新安装它。
猜你喜欢
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 2016-02-14
相关资源
最近更新 更多