What is the purpose of the dbconn class in the PHP code provided?
The purpose of the dbconn class in the PHP code provided is to establish a connection to a MySQL database. The class contains methods for connecting to the database, executing queries, and fetching results. It helps in encapsulating the database connection logic and provides a reusable way to interact with the database throughout the application.
<?php
class dbconn {
private $servername;
private $username;
private $password;
private $dbname;
private $conn;
public function __construct($servername, $username, $password, $dbname) {
$this->servername = $servername;
$this->username = $username;
$this->password = $password;
$this->dbname = $dbname;
$this->conn = new mysqli($this->servername, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
public function query($sql) {
return $this->conn->query($sql);
}
public function fetch($result) {
return $result->fetch_assoc();
}
public function close() {
$this->conn->close();
}
}
// Example usage
$db = new dbconn("localhost", "username", "password", "database_name");
$result = $db->query("SELECT * FROM table_name");
while ($row = $db->fetch($result)) {
// Process each row
}
$db->close();
?>