phpcodeignitercodeigniter-3

getting the 1st row in a database


I want to get the 1st row of the result depends on which build the room is. For example Building 1 have 1-200 rooms and Building 2 have 201-400 rooms. The code I tried is below. I have used the MIN in the where clause but I got all the rooms instead of having one.

$query = $this->db->query("SELECT * FROM `ha_utility_reading`");
if ($query->num_rows == 0) {

    echo "some data match";
    $lastroom = $this->db->select("*")->from("rooms")
      ->where("(SELECT MIN(room_num) FROM ha_rooms) and bldg_num = '$bldg_num'")
      ->get()->result_array();

    foreach($lastroom as $key => $test) {
        $output['room_num'][] = $test['room_num'];
        json_encode($output);
    }

Solution

  • You get all the rows because you need a group by clause. Anyway, the best way to do this is just adding this to your query:

    order by room_num asc limit 1;