Reputation: 704
I am querying and returning a numeric column from a MySQL table to a json array. However, when I try to access the last element in the array, it returns it as a string. I tried casting it with an int, but then it returns a 0. Here is my code:
public function get_latest_subcategory_id() {
$ids = $this->query("SELECT SubCategory_ID FROM SubCategory");
if ($ids->num_rows > 0) {
$arr_json = array();
while ($row = $ids->fetch_row()) {
$json = json_encode($row);
$arr_json[] = $json;
}
echo $arr_json[$ids->num_rows-1];
} else
return null;
}
Is there a way I can retrieve it as an integer?
Upvotes: 1
Views: 414
Reputation: 5876
The JSON doesn't really do anything here. It's also really inefficient to go through the entire database just to get the last row. Why not do something like this?
public function get_latest_subcategory_id() {
$ids = $this->query("SELECT SubCategory_ID FROM SubCategory ORDER BY SubCategory_ID DESC LIMIT 1");
if ($ids->num_rows > 0) {
$row = $ids->fetch_row();
return intval($row[0]);
} else
return null;
}
Upvotes: 2