在PHP中,可以使用MySQL Class來創建對象并與MySQL數據庫進行交互。以下是一個簡單的示例:
首先,確保已經安裝了MySQLi擴展,以便在PHP中使用MySQL數據庫。
創建一個名為config.php
的文件,用于存儲數據庫連接信息:
<?php
// config.php
define('DB_HOST', 'localhost');
define('DB_USER', 'your_username');
define('DB_PASS', 'your_password');
define('DB_NAME', 'your_database_name');
?>
MySQLClass.php
的文件,用于定義MySQL Class:<?php
// MySQLClass.php
class MySQL {
private $conn;
public function __construct() {
$this->connect();
}
private function connect() {
$this->conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($this->conn->connect_error) {
die("連接失敗: " . $this->conn->connect_error);
}
}
public function query($sql) {
return $this->conn->query($sql);
}
public function fetchArray($result) {
return $result->fetch_array();
}
}
?>
User.php
的文件,用于定義User類:<?php
// User.php
require_once 'MySQLClass.php';
class User {
private $mysql;
public function __construct() {
$this->mysql = new MySQL();
}
public function getUsers() {
$sql = "SELECT * FROM users";
$result = $this->mysql->query($sql);
$users = array();
while ($row = $this->mysql->fetchArray($result)) {
$users[] = $row;
}
return $users;
}
}
?>
index.php
)中,創建一個User類的實例,并調用getUsers()
方法來獲取用戶列表:<?php
// index.php
require_once 'User.php';
$user = new User();
$users = $user->getUsers();
foreach ($users as $user) {
echo "ID: " . $user['id'] . " - Name: " . $user['name'] . "<br>";
}
?>
這樣,就可以通過MySQL Class創建對象并與MySQL數據庫進行交互了。