host = $host; $this->username = $username; $this->password = $password; $this->database = $database; } /** * Connect to the database * * @return bool True if connection successful, false otherwise */ public function connect() { try { // Create connection using mysqli $this->connection = new mysqli($this->host, $this->username, $this->password, $this->database); // Check connection if ($this->connection->connect_error) { throw new Exception("Connection failed: " . $this->connection->connect_error); } return true; } catch (Exception $e) { echo "Error: " . $e->getMessage(); return false; } } /** * Execute a query against the database * * @param string $query SQL query to execute * @return mixed Query result set or false on failure */ public function executeQuery($query) { if (!$this->connection) { echo "Error: No active database connection"; return false; } try { $result = $this->connection->query($query); if ($result === false) { throw new Exception("Query execution failed: " . $this->connection->error); } return $result; } catch (Exception $e) { echo "Error: " . $e->getMessage(); return false; } } /** * Fetch all rows from a result set as an associative array * * @param mixed $result Query result set * @return array Array of rows or empty array on failure */ public function fetchAllRows($result) { $rows = []; if ($result && $result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $rows[] = $row; } } return $rows; } /** * Close the database connection */ public function closeConnection() { if ($this->connection) { $this->connection->close(); } } } // Example usage: /* // Create instance with connection details $db = new DatabaseConnector("localhost", "username", "password", "database_name"); // Connect to database if ($db->connect()) { // Execute a query $query = "SELECT * FROM users WHERE active = 1"; $result = $db->executeQuery($query); // Process the results if ($result) { $rows = $db->fetchAllRows($result); // Display the results foreach ($rows as $row) { echo "User ID: " . $row['id'] . ", Name: " . $row['name'] . "
"; } } // Close the connection $db->closeConnection(); } */ ?>