How can a PHP class be extended to work with MySQL for an artificial intelligence project?
To extend a PHP class to work with MySQL for an artificial intelligence project, you can create a new class that inherits from a base class that handles MySQL database connections and queries. This new class can then implement specific methods or functions related to the artificial intelligence functionality while utilizing the database connection provided by the base class.
<?php
// Base class for MySQL database connection
class MySQLDatabase {
protected $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) {
return $this->connection->query($sql);
}
public function close() {
$this->connection->close();
}
}
// AI class that extends MySQLDatabase
class AIWithMySQL extends MySQLDatabase {
public function getAIResults() {
$sql = "SELECT * FROM ai_results";
$result = $this->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "AI Result: " . $row["result"] . "<br>";
}
} else {
echo "No AI results found";
}
$this->close();
}
}
// Usage
$ai = new AIWithMySQL("localhost", "username", "password", "database_name");
$ai->getAIResults();
?>
Related Questions
- What are the best practices for using preg_match_all to extract specific content from HTML in PHP?
- What are some best practices for efficiently managing and displaying the total number of online users in a PHP application?
- What are the limitations of free hosting services in terms of executing PHP scripts and handling Javascript requirements?