How can using a DB class help in efficiently managing and tracking queries in PHP?
Using a DB class can help in efficiently managing and tracking queries in PHP by centralizing database connection logic, providing methods for executing queries, handling errors, and logging query execution. This can help in maintaining a clean and organized codebase, improving code reusability, and making it easier to monitor and optimize database interactions.
class DB {
private $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
public function query($sql) {
$result = $this->connection->query($sql);
if (!$result) {
die("Query failed: " . $this->connection->error);
}
return $result;
}
public function fetchArray($result) {
return $result->fetch_assoc();
}
public function numRows($result) {
return $result->num_rows;
}
public function escapeString($value) {
return $this->connection->real_escape_string($value);
}
public function close() {
$this->connection->close();
}
}
// Example usage
$db = new DB('localhost', 'username', 'password', 'database');
$result = $db->query("SELECT * FROM users");
while ($row = $db->fetchArray($result)) {
echo $row['name'] . "<br>";
}
$db->close();
Keywords
Related Questions
- How can one ensure that all image references are correctly set when transitioning from framesets to PHP for website development?
- Why is it important to only have one thread per topic in a PHP forum like PHP.de?
- How can the use of mysql_error() help in troubleshooting issues related to mysql_real_escape_string?