我有一個顯示用戶資訊的表單,當我加載 userpage.php 時,所有資訊都出現在每個欄位中,用戶可以編輯他的資訊,一切都很好,直到用戶單擊保存按鈕,它必須顯示具有更新資訊的相同表單,資料庫中的資料已更新,但用戶單擊保存時不會出現新資料。
這是單擊保存按鈕后的表單欄位值:
注意:嘗試訪問第27行 C:\xampp\htdocs\server\userpage.php 中null 型別值的陣列偏移注意:嘗試訪問C:\xampp\htdocs\server\ 中null 型別值的陣列偏移第28行的userpage.php注意:嘗試訪問第29行C:\xampp\htdocs\server\userpage.php中型別為 null 的值的陣列偏移
這是 userpage.php 檔案:
<?php
session_start();
include 'connection.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Account</title>
</head>
<body>
<?php
if(isset($_SESSION['Status'])){
echo "<h2>".$_SESSION['Status']."<h2>";
unset($_SESSION['Status']);
}
$id = $_POST['loginID'];//a get this from login page
$_SESSION['nid'] = $id; //To use it in update file
$query = "SELECT id, username, phone, email FROM user WHERE id ='$id';";
$result = mysqli_query($conn,$query);
$info =mysqli_fetch_array($result);
?>
<form id="profile" action="update.php" method="post">
<fieldset>
<input type="text" name="username" id="username" value="<?php echo $info['username'] ?>" >
<input type="tel" name="phone" id="phone" value="<?php echo $info['phone'] ?>" >
<input type="email" name="email" id="email" value="<?php echo $info['email'] ?>">
<input class="button" type="submit" name="save" value="save">
</fieldset>
</form>
</body>
</html>
Update.php 檔案代碼:
<?php
session_start();
include 'connection.php';
if(isset($_POST['save'])){
$id = $_SESSION['nid']; //Get the id from userpage.php file
$phone = $_POST['phone'];
$email = $_POST['email'];
$query = "UPDATE user SET phone='$phone', email='$email' WHERE id='$id'";
$result = mysqli_query($conn,$query);
if($result){
$_SESSION['Status'] = "Updated";
header('location: userpage.php');
}
else{
$_SESSION['Status'] = "Not updated";
header('location: userpage.php');
}
}
?>
uj5u.com熱心網友回復:
在您的 userpage.php 上。您$id通過 POST 方法獲得,但在頁面 update.php 中,您重定向回 userpage.php。重定向是 GET 方法,這就是您丟失 ID 的原因。
為了防止這種情況,請使用已經設定的會話。
首先,洗掉您的 2 行代碼。
$id = $_POST['loginID'];//a get this from login page
$_SESSION['nid'] = $id; //To use it in update file
并用這個替換。
$id = ($_POST['loginID'] ?? null);// use null coalesce operator to prevent undefined index.
// the $_POST['loginID'] code above still get the value that send via method POST from login page.
if ($id !== '' && !is_null($id)) {
// if id is not empty and not null. I don't check with empty() function to allow zero (0) value.
// set it to session.
$_SESSION['nid'] = $id;
} elseif (isset($_SESSION['nid'])) {
// if session nid was set, use it.
// this condition will work on redirected back.
$id = $_SESSION['nid'];
} else {
// if come to this condition, it means that you have no ID at all!
// do whatever you want such as redirect to logout page for login again.
}
然后你就可以$id像以前一樣使用了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/373250.html
上一篇:Discord.js表單
