0

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?

2
  • 1
    $db belongs in the connect() function scope. Why not treat $db as a class property instead and access it via $class->db? Commented Jan 8, 2020 at 11:56
  • 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 any MYSQLI_ based script you want to debug ini_set('display_errors', 1); ini_set('log_errors',1); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);. This will force any MYSQLI_ errors to generate an Exception that you can see on the browser as well as normal PHP errors. Commented Jan 8, 2020 at 12:04

2 Answers 2

0

Make a property that all methods can share:

<?php

class Database 
{
    private $db;

    public function __construct() 
    {
        define('DB_HOST', 'localhost');
        define('DB_NAME', 'university');
        define('DB_USER', 'root');
        define('DB_PASSWORD', 'root');
        $this->db = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
    }

    public function query($sql)
    {
        return mysqli_query($this->db, $query);
    }
}

And then refactor your function

function Information()
{
    $db = new Database();
    $sql = "SELECT * FROM student WHERE id "; 
    $result = $db->query($sql);
    while($row = mysqli_fetch_array($result)) {
         echo $row['name'];
    }
}

Information();
Sign up to request clarification or add additional context in comments.

Comments

-1

The variable db is unknown to the function on this line:

Since $dbis a class property, just create it as a variable in the class

 private $db;

and set it in the connect function as mentioned by delboy1978uk like this:

$this->db = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);

2 Comments

Your solution will not work as you call connect() statically. $this won't wiork
@delboy1978uk updated it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.