Reputation: 11
I'm trying to get the last modified rows from the database, now I have it like this:
My table:
My table:
id fort_id Last modified
------------------------------
1 1 today
2 1 yesterday
3 2 today
4 2 yesterday
5 2 day be4 yesterday
6 3 today
------------------------------
I want to get the info like this:
id fort_id Last modified
------------------------------
1 1 today
3 2 today
6 3 today
------------------------------
Now this is what my code currently is:
$sql = "SELECT f.id, f.lat, f.lon, f.name, f.url, s.fort_id, s.team, s.last_modified, s.slots_available
FROM forts AS f
LEFT JOIN fort_sightings AS s ON f.id=s.fort_id
ORDER BY s.last_modified DESC";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
$sql_defender = "SELECT pokemon_id, owner_name, cp
FROM gym_defenders
WHERE fort_id = " . $row['id'] . "
ORDER BY cp DESC";
$result_defender = $mysqli->query($sql_defender);
$encode_defender = [];
while($defender = $result_defender->fetch_assoc()) {
$encode_defender[] = array("mon_cp" => $defender['cp'],
"mon_owner" => $defender['owner_name'],
"mon_id" => $defender['pokemon_id']);
}
$url = preg_replace("/^http:/i", "https:", $row['url']);
if($row['team'] == 1){ $team = "mystic";}
if($row['team'] == 2){ $team = "valor";}
if($row['team'] == 3){ $team = "instinct";}
$encode[] = array("id" => $row['id'],
"name" => $row['name'],
"image" => $url,
"team" => $team,
"modified" => $row['last_modified'],
"spots" => $row['slots_available'],
"lat" => $row['lat'],
"lng" => $row['lon'],
"defenders" => $encode_defender);
}
echo json_encode($encode, JSON_NUMERIC_CHECK);
This code should be like that there should be picked 1 fort_id every time with the latest last_modified one.
Upvotes: 0
Views: 43
Reputation:
You need to use GROUP BY i.e.
$sql = "SELECT f.id, s.fort_id, s.last_modified
FROM forts AS f LEFT JOIN fort_sightings AS s ON f.id=s.fort_id
GROUP BY s.fort_id
ORDER BY s.last_modified DESC";
$result = $mysqli->query($sql);
Upvotes: 1