php - Displaying array content from function?
310
Can anyone tell me how to display the value of next from the code below?
In my user.php file i have next content:
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('#[^[email protected]_.-]#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;
}
}
In my index php file when I try:
$User = new User();
print_r($User->UserInfoQuery());
I have next results:
Array ( [0] => firstname [1] =>
lastname [2] =>
1990-11-23 [3] =>
male [4] =>
mail [5] =>
Srbija [6] => town )
How I can echo just the first and last names?
Answer
Solution:
This:
assigns the value of
$row['firstName']
to the variable$userFirstname
, then puts the result of the assignment (the value of$row['firstName']
) into an array. It's the same as writing:To declare an array with the key
userFirstname
, you need to write:From here, you have a normal array you can access:
This does seem somewhat clunky though, and honestly, you're not using objects very well here. You should save the data queried from the database into properties of the object, then use getters to access those properties one by one or all together. How to design a proper object is a little beyond the scope/point of this answer though.
Answer
Solution:
You should have your array the following way: