php - 连接apache到mysql数据库

标签 php mysql mysqli

作为作业的一部分,我正在尝试将我的 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();

    ?>

Error: Warning: mysqli::mysqli(): (HY000/2002): No such file or directory in /Library/WebServer/Documents/promos/index.php on line 8

Warning: mysqli::autocommit(): Couldn't fetch mysqli in /Library/WebServer/Documents/promos/index.php on line 9

Warning: mysqli::prepare(): Couldn't fetch mysqli in /Library/WebServer/Documents/promos/index.php on line 20

Fatal error: Call to a member function execute() on a non-object in /Library/WebServer/Documents/promos/index.php on line 21

请告诉我导致此问题的原因以及如何解决此问题。

最佳答案

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

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

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

关于php - 连接apache到mysql数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29848082/

相关文章:

mysql - N :M MySQL relation 中的 DISTINCT 和 COUNT

php - MySQL将字段结果乘以另一个字段的编号

php - 如何获得 SQL 中重复项求和的最佳项?

php - Imagick 在指定区域的图像上居中放置文本

php - 无法在 PHP5.6-apache 容器中安装 memcached 包

javascript - Bootstrap 按钮-单选值未设置

php - 在 PHP 中发布数组

php - 使用php从数据库访问数据并将数据输出到HTML

MySQL - 加速查询避免文件排序和临时

php - mysql UPDATE 多行多键 效率