2009-04-14 37 views
0

下面是我的遊戲註冊表格,它正在尋找用戶可能已經完成的錯誤,但即使發現錯誤,它也不會將其添加到$errors陣列中。當我print_r數組它返回空。數組總是回來爲空

我相信if函數有問題,因爲如果我從if函數之外添加一個值到數組中,它會添加它。

這裏是我的代碼:

if (isset($_GET['action'])){ 
db_connect(); 
db_select(); 

if ($_GET['action'] == "register"){ 
    $username = $_POST['username']; 
    $password = $_POST['password']; 
    $confirm = $_POST['confirm']; 
    $email = $_POST['email']; 
    $agree = $_POST['agree']; 

    $errors = array(); 
    if (!isset($username)){ 
    $errors['0'] = "You did not specifiy a username"; 
    }elseif (ereg("[^a-z0-9]", $username)) { 
    $errors_array['0'] = "Usernames can only contain lowercase letters and numbers"; 
    }elseif (mysql_num_rows(mysql_query("SELECT username FROM users WHERE username = '{$username}'")) > 0) { 
    $errors['0'] = "The username you chose has already been taken"; 
    } 

    if (!isset($password)){ 
    $errors['1'] = "You did not specify a password"; 
    }elseif ($password != $confirm){ 
    $errors['1'] = "The password and password confirm fields do not match"; 
    } 

    if (!isset($email)){ 
    $errors['2'] = "You did not specify a E-mail address"; 
    }elseif (mysql_num_rows(mysql_query("SELECT email FROM users WHERE email = '{$email}'")) > 0) { 
    $errors['2'] = "The E-mail you specified is already being used"; 
    } 
    print_r($errors); 
    } 
} 

回答

1

嘗試添加一個測試用例到陣列上創建。

$errors = array('test'=>'Test'); 

然後,如果您僅在print_r時收到此輸出,則您知道您的if語句未按預期工作。

沒有關於變量在輸入時有什麼值的更多信息,它很難調試。

也許做一個$ _POST(print_r($ _ POST))的轉儲,以確保你獲得了你認爲你的值。

2

那麼,我要做的第一件事就是不要通過鍵來解決你的數組問題。如果唯一的錯誤是沒有電子郵件地址,那麼你真的想要唯一的錯誤被索引'2'?

更好的用戶$錯誤[] =「的東西......「;

5

一些快速點:

  • 在一個地方,你使用的$errors_array代替$errors
  • 而不是使用索引時的寫入陣列,使用$errors[] = "some_error"這將在陣列的末尾添加some_error
1

在一個p花邊,你打電話給$ errors_array ['0'],你應該通過做$ errors [] =「Foo」添加到數組中。

第二請看if語句正在運行的Safe SQL

第三檢查。將echo "1";到您的每一個if語句(。和遞增1,這個數字爲每個展示然後你可以看到什麼實際運行(如果有的話))

8

首先你這樣做:

$username = $_POST['username']; 
$password = $_POST['password']; 
$confirm = $_POST['confirm']; 
$email = $_POST['email']; 
$agree = $_POST['agree']; 

然後你檢查$ username,$ password等isset()。這將始終返回true(因爲您剛初始化它們)。您應該對$ _POST變量(I.E.)執行if(isset()),而不是您創建的變量。因爲你沒有做檢查實際數據(有效的電子郵件地址,最小/最大用戶名長度等)的任何檢查,因此你所有的檢查都能正常工作。

發現這種問題的一種簡單方法是將error_reporting設置爲E_ALL。這將顯示所有錯誤/警告/通知/等。如果您使用一個不存在/尚未設置的變量,這將給您一個警告。

-1

解決了我自己的問題,我應該在我的if函數中使用「empty」而不是「!isset」。因爲它們設置如下顯示:

$username = $_POST['username']; 
$password = $_POST['password']; 
$confirm = $_POST['confirm']; 
$email = $_POST['email']; 
$agree = $_POST['agree']; 

無論如何感謝您的幫助。

+1

這是對問題的附錄(編輯)或對解決方案/問題的評論。但絕對不是答案。 – soulmerge 2009-04-15 07:39:44