So these are my codes.
model
function read() {
$sql= "SELECT * from table WHERE name = 'rabin'";
$query = $this->db->query($sql);
$res = $query->result_array();
return $res;
}
controller
function show() {
$this->load->model("db");
$array['data'] = $this->db->read();
$this->load->view("page", $array);
}
view
foreach($data as $val) {
"<p>" . echo $val['name']; . "</p>"
"<p>" . echo $val['address']; . "</p>"
}
Here, when there are no records in the database satisfying the WHERE clause in the query, the model returns null and I get error saying $data expects parameter 1 to be array, null given. There are several methods to deal with this situation. But, what would be the best possible way to handle this situation ?
if(is_array($data) && $data){foreach($data......if($data != FALSE){}then your code will become increasingly fragile. Imagine what would happen if$this->db->read();started returning a string as part of the varying output or anull, then you would have to back and re-factor yourif(){}blocks. However, if you structure your view to only act when it has received the expected data type then it will continue to do so. Continued below....if ($data) foreach ($data as $val)handle if there has result or not.