将apachec连接到mysql数据库

时间:2015-04-24 12:54:24

标签: 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();

    ?>
  

错误:警告:mysqli :: mysqli():( HY000 / 2002):没有这样的文件或   第8行/Library/WebServer/Documents/promos/index.php中的目录

     

警告:mysqli :: autocommit():无法获取mysqli   /Library/WebServer/Documents/promos/index.php第9行

     

警告:mysqli :: prepare():无法获取mysqli   /Library/WebServer/Documents/promos/index.php在第20行

     

致命错误:在非对象中调用成员函数execute()   第21行的/Library/WebServer/Documents/promos/index.php

请让我知道造成这种情况的原因以及如何解决这个问题。

1 个答案:

答案 0 :(得分:1)

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

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

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