我将从db中获取特定的性别,例如性别='男性'代码工作正常,但不能在foreach迭代它为什么
模型你可以检查
class get_all_gender extends CI_Model {
//put your code here
public function select_male() {
$this->db->select('*');
$this->db->from('bride_groom_register');
$this->db->where("gender='male'");
$query = $this->db->get();
if ($query->result() > 0)
{
return $query;
} else {
return FALSE;
}
}
}
和控制器我从数据库中获取数据
class Welcome extends CI_Controller {
public function index()
{
$this->load->model('get_all_gender');
$data['res']=$this->get_all_gender->select_male();
$this->load->view('list',$data);
}
}
简单视图
foreach ($res as $row)
{
echo $row->name;
}
答案 0 :(得分:1)
您应该返回$query
的{{1}}而不是result()
本身。您的模型应如下所示:
$query
您将结果保存在控制器中:
class Get_all_gender extends CI_Model {//put your code here
public function select_male() {
$this->db->where("gender","male");
$query = $this->db->get("bride_groom_register");
if ($query->num_rows() > 0) {
return $query->result();
} else {
return FALSE;
}
}
}
所以你可以在视图中这样访问它:
$data['res'] = $this->get_all_gender->select_male();
您应该检查FALSE条件,否则当模型没有返回任何行时,视图将抛出PHP错误。
答案 1 :(得分:1)
试试这个
在模型中
class get_all_gender extends CI_Model {
//put your code here
public function select_male()
{
$this->db->select('*');
$this->db->from('bride_groom_register');
$this->db->where("gender='male'");
$query = $this->db->get();
$result = $query->result_array();
if (!empty($result))
{
return $result;
}
else {
return FALSE;
}
}
}
在控制器中
class Welcome extends CI_Controller {
public function index()
{
$this->load->model('get_all_gender');
$data['res'] = $this->get_all_gender->select_male();
$this->load->view('list',$data);
}
}
在视图中
if ($res != FALSE) {
foreach ($res as $value) {
echo $value;
}
}
else {
echo "Seleted Category is Empty";
}
答案 2 :(得分:0)
在模型
上尝试以下代码班级名字首字母大写
文件名: Get_all_gender.php
<?php
class Get_all_gender extends CI_Model {//put your code here
public function select_male() {
$this->db->select('*');
$this->db->from('bride_groom_register');
$this->db->where('gender', 'male');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
// Or
// return $query->row_array();
} else {
return FALSE;
}
}
}
观看
foreach ($res as $row)
{
echo $row['name'];
}
答案 3 :(得分:0)
班级名字首字母大写
class Get_all_gender extends CI_Model {//put your code here
public function select_male() {
$this->db->select('*');
$this->db->from('bride_groom_register');
$this->db->where("gender='male'");
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return FALSE;
}
}
}