如何从数据库读取用户头像并在网站用户列表页展示?
实现用户列表页展示头像与用户名
步骤1:确保数据库表包含头像路径字段
先在users表中添加存储头像路径的字段,建议命名为profile_pic,字段类型设为VARCHAR(255),允许为空(适配未上传头像的用户)。
步骤2:完善头像上传的数据库存储逻辑
修改profilepicture.php代码,在文件上传成功后,将头像路径写入当前用户的数据库记录:
if (isset($_FILES['pp']['name']) AND !empty($_FILES['pp']['name'])) { $img_name = $_FILES['pp']['name']; $tmp_name = $_FILES['pp']['tmp_name']; $error = $_FILES['pp']['error']; if($error === 0){ $img_ex = pathinfo($img_name, PATHINFO_EXTENSION); $img_ex_to_lc = strtolower($img_ex); $allowed_exs = array('jpg', 'jpeg', 'png'); if(in_array($img_ex_to_lc, $allowed_exs)){ $new_img_name = uniqid($uname, true).'.'.$img_ex_to_lc; $img_upload_path = '../upload/'.$new_img_name; move_uploaded_file($tmp_name, $img_upload_path); // 新增:将头像路径更新到users表 $update_sql = "UPDATE users SET profile_pic = ? WHERE username = ?"; $stmt = $conn->prepare($update_sql); // 存储前端可直接访问的路径,假设upload文件夹在网站根目录 $profile_pic_path = 'upload/'.$new_img_name; $stmt->bind_param("ss", $profile_pic_path, $uname); $stmt->execute(); $stmt->close(); } } }
步骤3:修改userlist.php展示头像与用户名
更新查询和页面渲染逻辑,读取头像路径并展示,同时处理无头像的情况:
<?php include "header.php"; include "db_conn.php"; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Home</title> <link rel="icon" type="image/x-icon" href="fotos/favicon.ico"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="css/style.css"> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="styletwo.css"> <script src="java/currentime.js"></script> </head> <body> <h3 style="text-align: center;">Users on the website</h3> <!-- 调整容器样式适配头像展示 --> <div id="usernamelist" style="border: solid black 1px; width: 300px; margin-left: auto; margin-right: auto; padding: 10px;"> <?php if ($user) { // 仅查询需要的字段,减少数据冗余 $sql = "SELECT username, profile_pic FROM users;"; foreach ($conn->query($sql) as $row) { // 设置默认头像路径,可根据实际路径调整 $avatar_path = !empty($row['profile_pic']) ? $row['profile_pic'] : 'fotos/default-avatar.png'; ?> <div style="display: flex; align-items: center; margin-bottom: 10px;"> <!-- 控制头像尺寸,添加圆角优化视觉 --> <img src="<?= $avatar_path ?>" alt="User Avatar" style="width: 40px; height: 40px; border-radius: 50%; margin-right: 10px;"> <!-- 转义用户名防止XSS攻击 --> <span><?= htmlspecialchars($row['username']) ?></span> </div> <?php } } else { header("Location: login.php"); exit; } ?> </div> <?php include "footer.php"; ?> </body> </html>
注意事项
- 确保
upload文件夹存在且具备写入权限,前端访问路径需与数据库存储路径一致。 - 使用
htmlspecialchars()转义用户名,避免XSS安全风险。 - 准备一张默认头像图片,放在指定路径下,保证未上传头像的用户也能显示正常占位图。
内容的提问来源于stack exchange,提问作者gamemaker7720
相关产品推荐
相关产品推荐

