从函数中显示数组内容?

时间:2011-07-20 23:24:13

标签: php mysql

有谁能告诉我如何从下面的代码中显示next的值?

在我的user.php文件中,我有下一个内容:

class User {
    protected $userID;
    protected $useremail;
    protected $userPassword;
    public function __construct() {
        $this->userID = preg_replace('#[^0-9]#i', '', 
            $_SESSION['user_id']);
        $this->useremail = preg_replace('#[^A-Za-z0-9@_.-]#i', '', 
            $_SESSION['user']);
        $this->userPassword = preg_replace('#[^A-Za-z0-9]#i', '', 
            $_SESSION['user_password']);
    }

public function UserInfoQuery() {
    $sql = "SELECT * FROM users WHERE id = 
       '$this->userID' AND email = '$this->useremail' AND 
        password = '$this->userPassword' LIMIT 1";
    $res = mysql_query($sql) or die(mysql_error()); 
    $userMatch = mysql_numrows($res);

    if ($userMatch == 1) {
        while($row = mysql_fetch_array($res)) {
            $userData = array(
                $userFirstname = $row['firstName'],
                $userLastname = $row['lastName'],
                $userBirthdate = $row['birthDate'],
                $userSex = $row['sex'],
                $userEmail = $row['email'],
                $userCountry = $row['country'],
                $userRegion = $row['region']);
            }
        }

        return $userData;
    }
}

在我尝试的时候在我的索引php文件中:

$User = new User();
print_r($User->UserInfoQuery());

我有下一个结果:

Array ( [0] => firstname [1] => 
    lastname [2] => 
    1990-11-23 [3] => 
    male [4] => 
    mail [5] => 
    Srbija [6] => town ) 

我如何才能回显名字和姓氏?

2 个答案:

答案 0 :(得分:3)

此:

array($userFirstname = $row['firstName'])

$row['firstName']的值赋给变量$userFirstname,然后将赋值结果($row['firstName']的值)放入数组中。这和写作一样:

$userFirstname = $row['firstName'];
array($row['firstName']);

要使用 userFirstname声明数组,您需要写:

array('userFirstname' => $row['firstName'])

从这里开始,您可以访问正常的数组:

$userinfo = $User->UserInfoQuery();
echo $userinfo['userFirstname'];

虽然这看起来有点笨拙,老实说,你在这里并没有很好地使用物体。您应该将从数据库中查询的数据保存到对象的属性中,然后使用getter逐个或全部访问这些属性。如何设计一个合适的对象有点超出了这个答案的范围/点。

答案 1 :(得分:0)

您应该按照以下方式使用数组:

$userData = array(
            'Firstname' = $row['firstName'],
            'lastname = $row['lastName'],
            'birthdate = $row['birthDate'],
            'sex = $row['sex'],
            'email = $row['email'],
            'country = $row['country'],
            'region = $row['region']
       );
}