2014-11-23 95 views
1

當我試圖回顯用戶的名稱時,出現錯誤。PHP未定義的索引:名稱

代碼選擇

public function profile($username){ 
    $result = mysql_query("SELECT * FROM " . PFX . "employees WHERE email ='$username'"); 
    $employee = array(); 
    while($rows = mysql_fetch_assoc($result)){ 
     $employee[] = $rows; 
    return $employee; 
    } 
} 

在頁面:

$employee = $user->profile($username); 
<?php echo $employee['name']; ?> 

我試過的print_r($員工);其輸出如下:

Array ([0] => Array ([id] => 4 [name] => Test Person... 

所以它得到從數據庫中的用戶,但它不能只是呼應的名稱,有人可以看到錯誤的?

我知道代碼沒有更新..

+1

? – jmn 2014-11-23 08:02:38

回答

2

正如你可以在你的print_r()看,其仍然嵌套在:

Array ([0] => Array ([id] => 4 [name] => Test Person... 
     ^another dimension inside. 

所以在訪問它:

$employee = $user->profile($username); 
<?php echo $employee[0]['name']; ?> 

必須注意:

Please, don't use mysql_* functions in new code。他們不再維護and are officially deprecated。請參閱red box?請改爲了解prepared statements,並使用PDOMySQLi - this article將幫助您決定哪個。如果您選擇PDO,here is a good tutorial
編號:https://stackoverflow.com/a/12860140/3859027

我建議使用PDO在這種情況下,準備語句:

public function profile($username) 
{ 
    $db = new PDO('mysql:host=localhost;dbname=DB_NAME', 'username', 'password'); 
    $sql = 'SELECT * FROM ' . PFX . 'exmployees WHERE email = :username'; 
    $select = $db->prepare($sql); 
    $select->bindParam(':username', $username); 

    return $select->fetch(PDO::FETCH_ASSOC); 
} 

然後,你可以這樣做:

$employee = $user->profile($username); 
<?php echo $employee['name']; ?> 
+0

錯過行的索引是很常見的。我之前有過同樣的錯誤:) – 2014-11-23 08:03:49

+0

謝謝,它工作:)! – 2014-11-23 08:04:31

+0

@MichaelWestergaard @MichaelWestergaard肯定這個人很高興這有幫助,我敦促你使用PDO與這一個準備的語句,因爲mysql已經被棄用,你的當前代碼很容易sql注入,因爲它直接在查詢語句中使用它的輸入。 – Ghost 2014-11-23 08:09:45

0

試試這個:

$employee[0]['name']; 
+0

您能否解釋您的答案,這將有助於OP更好地理解您提出的解決方案。 – 2014-11-23 10:13:40

0

將您的線路更改爲此。它將訪問在$員工的第一條記錄,然後將打印的名稱第一記錄

<?php echo $employee[0]['name']; ?> 
0

爲什麼回報是while循環裏面試試這個代碼

<?php echo $employee[0]."<br/>"; ?> 
<?php echo $employee[1]."<br/>"; ?> 
<?php echo $employee[2]."<br/>"; ?>