要从MySQL表中获取user_id
并使用jQuery设置HTML属性,你需要完成以下几个步骤:
以下是一个简单的示例,展示如何从MySQL数据库中获取user_id
并使用jQuery设置HTML属性。
<?php
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 查询user_id
$sql = "SELECT user_id FROM users";
$result = $conn->query($sql);
$user_ids = [];
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$user_ids[] = $row["user_id"];
}
} else {
echo "0 结果";
}
$conn->close();
// 将user_ids传递给前端
echo json_encode($user_ids);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User IDs</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="user-info">
<!-- 用户信息将在这里动态生成 -->
</div>
<script>
$(document).ready(function() {
$.ajax({
url: 'path_to_your_php_script.php', // 替换为你的PHP脚本路径
method: 'GET',
dataType: 'json',
success: function(user_ids) {
user_ids.forEach(function(user_id) {
$('#user-info').append(
'<div>' +
'<img src="path_to_images/' + user_id + '.jpg" alt="User Image">' +
'<a href="user_profile.php?id=' + user_id + '">Profile</a>' +
'<h3>User ID: ' + user_id + '</h3>' +
'</div>'
);
});
},
error: function(xhr, status, error) {
console.error("Error fetching user IDs: ", error);
}
});
});
</script>
</body>
</html>
通过以上步骤和代码示例,你应该能够成功地从MySQL表中获取user_id
并使用jQuery动态设置HTML属性。
领取专属 10元无门槛券
手把手带您无忧上云