我为我做了这项工作,但我确信有更好的方法来完成这项工作。但是,我已经搜索了很多个小时而没有找到我想要做的事情的确切答案。基本上从URL获取变量usrID,我需要在MySQL中搜索相应的信息给这个用户。后来我想使用我页面上的不同字段(更好的网站)来个性化体验。
<?php
$servername = "localhost";
$username = "authorized-user";
$password = "secret";
$dbname = "agentDB";
$usrID = "001";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM agentInfo WHERE usrID = '$usrID'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$Lname = $row["Lname"];
$Fname = $row["Fname"];
$tl = $row["tl"];
}
}
mysqli_close($conn);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Load MySQL Data into Corresponding PHP Variables</title>
</head>
<body>
here is the body<br>
My name is: <?php echo $Fname; ?> <?php echo $Lname; ?><?php echo $tl; ?>
</body>
</html>
答案 0 :(得分:0)
你可以创建一个变量来存储一个全名,然后像这样“tl”:
$user_info = $Lname . ", " . $Fname . ": " . $tl;
然后:
<?php echo $user_info; ?>
无论您何时需要该信息。
如果要最小化分配的变量数量,可以将其包装在函数中并返回所需的数据字段:
function fetchUserData(userData) {
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM agentInfo WHERE usrID = '$usrID'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$userData = $row[userData];
}
}
return $userData;
}
mysqli_close($conn);
您可以像这样获取指定的数据:
<?php echo fetchUserData("Fname"); ?>