As a part of assignment I am trying to connect my Apache server to MySql database.
I have verified that my Apache is working with following code:
<?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();
?>
But when I replace this code to read from my database it gives me following error:
<?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
Please let me know what is causing this and how can i resolve this.