我正在运行for循环来从论坛表中收集数据,但是如果没有返回结果,我不太清楚如何处理它。这是我必须收集数据的代码。
$q = $this->db->query("SELECT * FROM newslist ORDER BY pubdate DESC");
if ($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$data[] = $row;
}
}
return $data; else {
return echo = "nose";
}
答案 0 :(得分:1)
$q = $this->db->query("SELECT * FROM newslist ORDER BY pubdate DESC");
$data = array(); // Initialize the array in case there are no records.
if ($q->num_rows() > 0){
foreach ($q->result() as $row){
$data[] = $row;
}
}
if (empty($data)) { // If there are no records, $data will be empty.
return "nose";
}
else { // If $data has records, will return data from SQL.
return $data;
}
<强>解释强>
1)初始化$data
变量。如果我们没有得到任何记录,则不会追加$data
,导致初始化变量$data
返回错误。通过在循环之前初始化它,我们正在克服它。
2)检查empty()
的{{1}},如果为空,则返回错误字符串,否则为$data
。
答案 1 :(得分:0)
流量问题的一点点。见修订后的解决方案。
$q = $this->db->query("SELECT * FROM newslist ORDER BY pubdate DESC");
if($q->num_rows() > 0){
foreach($q->result() as $row){
$data[] = $row;
}
return $data;
} //<-- this was on the wrong line
else {
return "No data!";
}
答案 2 :(得分:0)
在if
条件下返回您的数据,不要同时使用return and echo
。
$q = $this->db->query("SELECT * FROM newslist ORDER BY pubdate DESC");
if ($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$data[] = $row;
}
return $data;// return data inside if condition
}
else {
return "nose";// remove echo from here
}
答案 3 :(得分:0)
只需您可以使用此
$query = $this->db->query("SELECT * FROM newslist ORDER BY pubdate DESC");
$result = $query->result_array();
$count = count($result);// counting data
if(empty($count))
{
$log = 'nose';
return $log;
}
else
{
return $result;
}