I adopted code given in this example: PHP database connection class
But i changed the code with the link above and it is as follows:
class Database {
public function connect() {
define('DB_HOST', 'localhost');
define('DB_NAME', 'university');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');
$db = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
}
}
function Information(){
Database::connect();
$query = "SELECT * FROM student WHERE id "; $result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result)) {
echo $row['name'];
}
}
Information();
It gives error:
Notice: Undefined variable: db in /Applications/XAMPP/file.php on line 12.
What could be the reason and what am I doing wrong?
$dbbelongs in theconnect()function scope. Why not treat$dbas a class property instead and access it via$class->db?WHERE id?? think it would also be useful to show errors. To get errors out of PHP even in a LIVE environment add these 4 lines to the top of anyMYSQLI_based script you want to debugini_set('display_errors', 1); ini_set('log_errors',1); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);. This will force anyMYSQLI_errors to generate an Exception that you can see on the browser as well as normal PHP errors.