PHP未定义索引:名称

时间:2014-11-23 07:59:36

标签: 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($ employee);输出如下:

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

所以它确实从数据库中获取了用户,但它只能回显名称,有人可以看到错误的位置吗?

我知道代码没有更新..

4 个答案:

答案 0 :(得分: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']; ?>

答案 1 :(得分:0)

试试这个:

$employee[0]['name'];

答案 2 :(得分:0)

将您的行更改为此。它将访问$ employee中的第一条记录,然后将打印第一条记录的名称

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

答案 3 :(得分:0)

试试此代码

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