I have a ‘Database.php’ that would handle database connections and would hand over mysql connections to classes that calls the Database class.
Database.php
<?php
class Database {
private $domain = "localhost";
private $usr = "root";
private $pwd = "password";
private $dbname = "testdb";
private $db;
function __contruct() {
}
function connect() {
$this->db = mysqli_connect($domain, $usr, $pwd, $dbname);
if ($db->connect_errno > 0) {
die("DbConn Fail: \n ".$mysqli->connect_error);
} else {
return $this->db;
}
}
}
?>
I have the following test class trying to call the Database class to retrieve a connection and then use the connection in it’s SQl statements …
test.php
<?php
include('Database.php');
$db = new Database();
$conn = $db->connect();
$sql = "SELECT custid FROM `testdb`.`customer`";
$res = mysqli_query($conn, $sql);
$nrows = mysqli_num_rows($res);
echo "Num Rows Found: " . $nrows . "<br>";
if($res) {
echo "fetching...<br>";
while ($row = mysqli_fetch_assoc($res)){
echo "Found Customer ID: " . $row['custid'] . "<br>";
}
}
?>
The problem I am facing is within the ‘Database.php’ class. Whenever a successful connection is established via the ‘connect()’ function, the Database class would return a valid mysql connection to the class calling the ‘Database’ class but from the demo below it is not working as intended.
May I know what I should do to fix the above problem ?
You should include the link and not the class initialization:
also your connection is wrong:
also: