· 10 months ago · Feb 26, 2025, 02:40 PM
1<?php
2
3class DatabaseConnector {
4 private $host;
5 private $username;
6 private $password;
7 private $database;
8 private $connection;
9
10 /**
11 * Constructor - initialize database connection parameters
12 *
13 * @param string $host Database server hostname
14 * @param string $username Database username
15 * @param string $password Database password
16 * @param string $database Database name
17 */
18 public function __construct($host, $username, $password, $database) {
19 $this->host = $host;
20 $this->username = $username;
21 $this->password = $password;
22 $this->database = $database;
23 }
24
25 /**
26 * Connect to the database
27 *
28 * @return bool True if connection successful, false otherwise
29 */
30 public function connect() {
31 try {
32 // Create connection using mysqli
33 $this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);
34
35 // Check connection
36 if ($this->connection->connect_error) {
37 throw new Exception("Connection failed: " . $this->connection->connect_error);
38 }
39
40 return true;
41 } catch (Exception $e) {
42 echo "Error: " . $e->getMessage();
43 return false;
44 }
45 }
46
47 /**
48 * Execute a query against the database
49 *
50 * @param string $query SQL query to execute
51 * @return mixed Query result set or false on failure
52 */
53 public function executeQuery($query) {
54 if (!$this->connection) {
55 echo "Error: No active database connection";
56 return false;
57 }
58
59 try {
60 $result = $this->connection->query($query);
61
62 if ($result === false) {
63 throw new Exception("Query execution failed: " . $this->connection->error);
64 }
65
66 return $result;
67 } catch (Exception $e) {
68 echo "Error: " . $e->getMessage();
69 return false;
70 }
71 }
72
73 /**
74 * Fetch all rows from a result set as an associative array
75 *
76 * @param mixed $result Query result set
77 * @return array Array of rows or empty array on failure
78 */
79 public function fetchAllRows($result) {
80 $rows = [];
81
82 if ($result && $result->num_rows > 0) {
83 while ($row = $result->fetch_assoc()) {
84 $rows[] = $row;
85 }
86 }
87
88 return $rows;
89 }
90
91 /**
92 * Close the database connection
93 */
94 public function closeConnection() {
95 if ($this->connection) {
96 $this->connection->close();
97 }
98 }
99}
100
101// Example usage:
102/*
103// Create instance with connection details
104$db = new DatabaseConnector("localhost", "username", "password", "database_name");
105
106// Connect to database
107if ($db->connect()) {
108 // Execute a query
109 $query = "SELECT * FROM users WHERE active = 1";
110 $result = $db->executeQuery($query);
111
112 // Process the results
113 if ($result) {
114 $rows = $db->fetchAllRows($result);
115
116 // Display the results
117 foreach ($rows as $row) {
118 echo "User ID: " . $row['id'] . ", Name: " . $row['name'] . "<br>";
119 }
120 }
121
122 // Close the connection
123 $db->closeConnection();
124}
125*/
126?>