2013-10-09 84 views
0

我想從頭開始創建一個論壇,並且我有點糾結。在下面的代碼中,我試圖把一個條件,如果用戶沒有登錄,他不能添加一個類別。然而,如果用戶登錄,代碼完美工作,但我得到一個「未定義的索引:如果他不是,我試圖添加if(isset($_SESSION['userid'])),但這只是隱藏了」你必須登錄「的通知。 ?糾結..未定義的索引通知

<?php 

include("_/inc/dbcon.php"); 
    $link = mysql_connect($host, $login, $pw); 
    mysql_select_db($database); 
    if($link){ 
    } 
include("_/inc/session_handler.php"); 
$create_cat =""; 
if($_SESSION['userid'] == false /*| $_SESSION['rank'] !='Emperor' || $_SESSION['rank'] !='Destroyer' || $_SESSION['rank']!= 'Tekken Lord')*/) 
{ 
    //the user is not an admin 
    echo 'Sorry, you do not have sufficient rights to access this page.'; 
} 
else 
{ 
    //the user has admin rights 
    if($_SERVER['REQUEST_METHOD'] != 'POST') 
    { echo "YOU HAVE THE RIGHTS!"; 
     //the form hasn't been posted yet, display it 

     $create_cat .= '<form method="post" action=""> 
      <input type="text" name="cat_name" placeholder="Category Name"/><br /> 
      <input type="text" name="cat_description" placeholder="Category Description" /><br /> 
      <input type="submit" value="Add category" /> 
     </form>'; 
    } 
    else 
    { 
     //the form has been posted, so save it 
     $sql = "INSERT INTO sp_categories(cat_name, cat_description) 
      VALUES('" . mysql_real_escape_string($_POST['cat_name']) . "', 
       '" . mysql_real_escape_string($_POST['cat_description']) . "')"; 
     $result = mysql_query($sql); 
     if(!$result) 
     { 
      //something went wrong, display the error 
      echo 'Error' . mysql_error(); 
     } 
     else 
     { 
      $create_cat .= 'New category succesfully added.'; 
     } 
    } 
} 

?> 
+0

從不使用mysql_函數。他們由於某種原因而被棄用。改爲使用[mysqli](http://php.net/manual/en/book.mysqli.php)或[PDO](http://php.net/manual/en/book.pdo.php)。 – euantorano

+0

[PHP:「注意:未定義變量」和「注意:未定義索引」]的可能重複(http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – halfer

+0

在這裏查看''''''''''側邊欄''>。大量的重複問題':)'。請始終在詢問之前進行搜索 - 它也會爲您節省時間! – halfer

回答

0

當你試圖調用數組的索引則發出未定義指數錯誤,沒有定義時。
例如:

// Define an array with a few keys and values... 
$data = array(
    'vehicle' => "car", 
    'color' => "red", 
); 
echo $data['size']; // This line will issue an undefined index error... 

...因爲指數大小不是現有的密鑰。

試圖調用它之前,請務必檢查陣列中的一個重要的存在:

if (isset($_SESSION['userid']) && $_SESSION['userid'] === false) 

PS:我注意到您使用mysql_*功能,已被棄用。請嘗試使用PDO代替。

+0

這是關於它。只是我需要說!ISSET。非常感謝 :) –

0

如果你真的確定你的代碼工作(即使這是一個壞榜樣),使用error_reporting(E_ERROR);刪除通知。

或者,也許你在錯誤的地方使用isset()