RDowns RDowns - 1 month ago 9
PHP Question

What is the reason this code only returns the first row in the array?

I'm looking to create a 'Drill-Down' UITable for my app.

The user will select

'country' > 'division' > 'team'
. Each currently exists as a separate table within my database and are linked by id.

I have written a PHP function to get the details of each table and put them in a single array to be sent to swift for use in the UITable.

However, this code currently only outputs:


{"countries":[{"id":"1","name":"Denmark"}],"divisions":[{"id":"1","country_id":"1","Name":"ALKA SUPERLIGA"}],"teams":[{"id":"1","division_id":"1","name":null}]}


And I would have expected this to retrieve everything

$countries = array();
$countries = getCountries($countries);

$divisions = array();
$divisions = getDivisions($divisions);

$teams = array();
$teams = Teams($teams);

public function getCountries()
{
$returnValue = array();
$sql = "select * from countries";

$result = $this->conn->query($sql);
if($result != null && (mysqli_num_rows($result) >= 1)){
$row = $result -> fetch_array(MYSQLI_ASSOC);
if(!empty($row)){
$returnValue[] = $row;
}
}
return $returnValue;

}

public function getDivisions()
{
$returnValue = array();
$sql = "select * from divisions";

$result = $this->conn->query($sql);
if($result != null && (mysqli_num_rows($result) >= 1)){
$row = $result -> fetch_array(MYSQLI_ASSOC);
if(!empty($row)){
$returnValue[] = $row;
}
}
return $returnValue;

}

public function getTeams()
{
$returnValue = array();
$sql = "select * from teams";

$result = $this->conn->query($sql);
if($result != null && (mysqli_num_rows($result) >= 1)){
$row = $result -> fetch_array(MYSQLI_ASSOC);
if(!empty($row)){
$returnValue[] = $row;
}
}
return $returnValue;

}

echo json_encode(array('countries' => $countries,'divisions' => $divisions,'teams' => $teams));


What is the reason it is only printing the first row?

On a secondary note, that null in teams should say 'Br√łndby IF' - has it kicked it out because of the special character?

Answer

You're not actually looping through the rows returned from the database. fetch_array fetches a single result row as an array. Try something like:

        while ($row = $result -> fetch_array(MYSQLI_ASSOC)) {
          $returnValue[] = $row;
        }
Comments