[英]Troubleshooting 'undefined variable' error
我不斷收到以下錯誤Undefined variable: password on line 33
如何解決此問題? 因此此錯誤將停止顯示。
這是PHP代碼。
$first_name = mysqli_real_escape_string($mysqli, $purifier->purify(htmlentities(strip_tags($_POST['first_name']))));
$password1 = mysqli_real_escape_string($mysqli, $purifier->purify(strip_tags($_POST['password1'])));
$password2 = mysqli_real_escape_string($mysqli, $purifier->purify(strip_tags($_POST['password2'])));
// Check for a password and match against the confirmed password:
if ($password1 == $password2) {
$sha512 = hash('sha512', $password1);
$password = mysqli_real_escape_string($mysqli, $sha512);
} else {
echo '<p class="error">Your password did not match the confirmed password!</p>';
}
//If the table is not found add it to the database
if (mysqli_num_rows($dbc) == 0) {
$mysqli = mysqli_connect("localhost", "root", "", "sitename");
$dbc = mysqli_query($mysqli,"INSERT INTO users (user_id, first_name, password)
VALUES ('$user_id', '$first_name', '$password')");
}
//If the table is in the database update each field when needed
if ($dbc == TRUE) {
$dbc = mysqli_query($mysqli,"UPDATE users
SET first_name = '$first_name', password = '$password'
WHERE user_id = '$user_id'");
echo '<p class="changes-saved">Your changes have been saved!</p>';
}
只有一個地方將值分配給$password
if ($password1 == $password2) {
$sha512 = hash('sha512', $password1);
$password = mysqli_real_escape_string($mysqli, $sha512);
}
因此,如果不滿足條件,將不會有$password
。 在這種情況下,無論如何都沒有必要執行UPDATE查詢。
在頂部定義
$password = '';
然后將DBC檢查更改為
if ($dbc == TRUE && $password != ''){
如您所見,無論第一個if()
是true還是false,都將完成數據庫插入。 如果為假($ password1和$ password2不匹配),則不會定義$ password。
如果此條件失敗:
if ($password1 == $password2) {
$password
將不會被定義,這將在以后使用的其中一行中引發錯誤。
您不會在$ password = ......行上使用ELSE語句引發錯誤,因此在此顯然存在錯誤且未定義。 頂級的if語句很好,但是錯誤在$ password聲明行上。 你知道那是怎么回事嗎?
如果插入失敗(大概是因為user_id已經存在-您已將主鍵設置為?),則可以重試查詢,而可以使用備用INSERT INTO ... ON DUPLICATE KEY UPDATE
語法:
INSERT INTO users (user_id, first_name, password)
VALUES ('$user_id', '$first_name', '$password')
ON DUPLICATE KEY UPDATE
first_name=VALUES(first_name),
password=VALUES(password)
有一點很奇怪,您的評論說“如果找不到表”和“如果表...”。 您無需處理表的創建/修改-您需要處理存儲在表中的記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.