搭建一個(gè)PHP Dashboard可以是一個(gè)復(fù)雜的過(guò)程,但也可以相對(duì)簡(jiǎn)單地完成。以下是一個(gè)基本的步驟指南,幫助你快速搭建一個(gè)簡(jiǎn)單的PHP Dashboard:
你可以創(chuàng)建一個(gè)基本的項(xiàng)目結(jié)構(gòu),例如:
/dashboard
/css
style.css
/js
script.js
/includes
db.php
functions.php
/templates
index.php
dashboard.php
index.php
在db.php
文件中創(chuàng)建數(shù)據(jù)庫(kù)連接:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dashboard_db";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
在templates
目錄下創(chuàng)建index.php
和dashboard.php
文件。
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h1>Welcome to the Dashboard</h1>
<a href="dashboard.php">Go to Dashboard</a>
</div>
</body>
</html>
dashboard.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h1>Dashboard</h1>
<div id="content"></div>
<script src="js/script.js"></script>
</div>
</body>
</html>
在functions.php
文件中編寫(xiě)函數(shù)來(lái)連接數(shù)據(jù)庫(kù)并獲取數(shù)據(jù):
<?php
include 'db.php';
function getDashboardData() {
global $conn;
$sql = "SELECT id, title, value FROM dashboard_data";
$result = $conn->query($sql);
$data = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
return $data;
}
?>
在dashboard.php
中使用JavaScript動(dòng)態(tài)顯示數(shù)據(jù):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h1>Dashboard</h1>
<div id="content"></div>
<script src="js/script.js"></script>
</div>
</body>
</html>
script.js:
document.addEventListener('DOMContentLoaded', function() {
fetch('/functions.php')
.then(response => response.json())
.then(data => {
const content = document.getElementById('content');
data.forEach(item => {
const div = document.createElement('div');
div.innerHTML = `<strong>${item.title}</strong>: ${item.value}`;
content.appendChild(div);
});
})
.catch(error => console.error('Error:', error));
});
確保你的Web服務(wù)器(如Apache或Nginx)已經(jīng)配置好,并且指向了你的項(xiàng)目目錄。
打開(kāi)瀏覽器,訪(fǎng)問(wèn)你的服務(wù)器地址(例如http://your_server_ip/dashboard
),你應(yīng)該能夠看到Dashboard界面并顯示數(shù)據(jù)。
這只是一個(gè)基本的示例,你可以根據(jù)需要進(jìn)一步擴(kuò)展和美化你的Dashboard。