I am creating a function that is suppose to get the first name and last name from the database and return the query. Something is not right about it though.
The first and last names don't show up. I'm not getting any errors or warnings and I've tried all of the answers provided on this site and others(there is not much though).
Can someone tell me what is wrong with it ?
public function getFirstAndLastName() {
$username = $this->user['username'];
$query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? ");
$query->bind_param("s", $username);
$query->execute();
$query_result = $query->get_result();
$query_result->fetch_array();
while ($row = $query_result->fetch_assoc()) {
$row['first_name'];
}
return $row;
}
First of all if you are trying to finding a better way you can use this one
public function getFirstAndLastName() {
$username = $this->user['username'];
$query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? ");
$query->bind_param("s", $username);
$query->execute();
$query_result = $query->get_result();
$result = $query_result->fetch_all(MYSQLI_ASSOC);
Return $result;
}
mysqli has a handy function that instantly returns an array from the query result: mysqli_fetch_all(). So instead of this lines
while ($row = $query_result->fetch_assoc()) {
$row['first_name'];
}
it could be just a single line:
$result = $query_result->fetch_all(MYSQLI_ASSOC);
if you are looking to finding the answer why your function will return null i will explain for you :
There is some mistake in your codes
first of all when you execute this line $query_result->fetch_array();
actually you just make empty the mysqli buffer! so you don't have anything in buffer to catch it in this line -> while ($row = $query_result->fetch_assoc()) {
and in other hand even if you had something in buffer then you dont do nothing in this line ->
$row['first_name'];
if you are looking to correct your codes you should write the code like this ->
first of all make comment this line -> $query_result->fetch_array();
public function getFirstAndLastName() {
$username = $this->user['username'];
$query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? ");
$query->bind_param("s", $username);
$query->execute();
$query_result = $query->get_result();
//$query_result->fetch_array();
while ($row = $query_result->fetch_assoc()) {
$result[] = $row['first_name'];
}
return $result;
}
Edit:
if you are looking to get both first name and last name you have to do like this ->
public function getFirstAndLastName() {
$username = $this->user['username'];
$query = $this->con->prepare("SELECT first_name, last_name FROM users WHERE username = ? ");
$query->bind_param("s", $username);
$query->execute();
$query_result = $query->get_result();
//$query_result->fetch_array();
while ($row = $query_result->fetch_assoc()) {
$result[] = $row;
}
return $result;
}