在PHP中,要存儲用戶信息,通常我們會使用數據庫來保存和管理這些數據。以下是使用PHP和MySQL存儲用戶信息的基本步驟:
CREATE DATABASE user_database;
USE user_database;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
$servername = "localhost";
$username = "your_database_username";
$password = "your_database_password";
$dbname = "user_database";
// 創建連接
$conn = new mysqli($servername, $username, $password, $dbname);
// 檢查連接
if ($conn->connect_error) {
die("連接失敗: " . $conn->connect_error);
}
function addUser($username, $password, $email) {
global $conn;
// 對密碼進行加密處理
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $conn->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $hashed_password, $email);
if ($stmt->execute()) {
echo "新用戶添加成功";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
}
addUser("testuser", "testpassword", "testuser@example.com");
function getUserInfo($id) {
global $conn;
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
return $user;
}
$user_id = 1;
$user_info = getUserInfo($user_id);
print_r($user_info);
function updateUser($id, $username, $password, $email) {
global $conn;
// 對密碼進行加密處理
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $conn->prepare("UPDATE users SET username = ?, password = ?, email = ? WHERE id = ?");
$stmt->bind_param("sssi", $username, $hashed_password, $email, $id);
if ($stmt->execute()) {
echo "用戶信息更新成功";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
}
function deleteUser($id) {
global $conn;
$stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
$stmt->bind_param("i", $id);
if ($stmt->execute()) {
echo "用戶信息刪除成功";
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
}
以上示例展示了如何使用PHP和MySQL存儲、查詢、更新和刪除用戶信息。在實際項目中,你可能還需要考慮其他因素,例如數據驗證、錯誤處理和安全性等。