How can the fetch_array function be properly utilized within a PHP class for mysqli database queries?
When using the fetch_array function within a PHP class for mysqli database queries, it is important to ensure that the function is called on the result object returned by the query execution. This can be achieved by passing the result object as a parameter to the fetch_array function within the class method that handles the query. By properly utilizing the fetch_array function in this manner, you can retrieve data from the database query result in an organized and efficient way within your PHP class.
class Database {
private $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
}
public function query($sql) {
$result = $this->connection->query($sql);
return $result;
}
public function fetchData($result) {
return $result->fetch_array(MYSQLI_ASSOC);
}
}
// Example usage
$db = new Database('localhost', 'username', 'password', 'database');
$result = $db->query("SELECT * FROM table_name");
$data = $db->fetchData($result);
// Access data
echo $data['column_name'];