【问题标题】:Codeigniter simple foreach Loop is not workingCodeigniter 简单的 foreach 循环不起作用
【发布时间】:2013-12-02 04:40:46
【问题描述】:

我不是第一次使用 foreach 循环。但是我第一次看到 foreach 循环不起作用。我检查了我的代码大括号,一切顺利。起初我将我的查询保存在一个模型中,之后我将脚本直接写入我的视图页面。但是,当我使用 foreach 时,不使用我的页面显示为空白。查询功能也起作用了。

这里是查询:

$homeigw = $this->db->query("SELECT * FROM data INNER JOIN trunk_info ON trunk_id = trunc_group WHERE trunk_type = 'igw'");
                                         foreach($homeigw->result() as $igww){
                                             echo $igww->id;
                                         }

这是我的查看页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Report Generator ASR/ACD</title>        
        <script type="text/javascript" src="<?php echo base_url();?>js/tcal.js"></script> 
        <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>style/tcal.css" />  
        <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>style/css/menu.css" /> 
        <style>
            #dashboard { width: 100%;height:auto;background-color: #ffffff;}
            #dashboard .dbox{width: 320px;height: 300px;float:left;padding: 5px;margin: 15px;border:  1px solid #cccccc;}
            #dashboard .dbox h2{background-color: #123;color: #FF9933;font-size: 10pt;font-weight: normal;padding-left:10px;height: 20px;text-align: center;padding-top:5px; }
            #dashboard .dbox ul li{word-spacing: 70px; }
            #dashboard .dbox ul li:hover{background-color: #123;color: #FFFFFF;  }
            #dashboard .dbox ul { width:280px;   height: 200px;overflow: scroll;}
            #dashboard .dbox p{width: 130px;padding: 5px;background-color: #123;margin-left:5px;color: #FF9933;}
            .floatleft{float:left;}
            .floatright{ float:right;}
        </style>
        <script type="text/javascript" src="<?php echo base_url(); ?>js/tabber.js"></script>
     <link rel="stylesheet" href="<?php echo base_url(); ?>js/example.css" TYPE="text/css" MEDIA="screen">
      <script type="text/javascript">
            document.write('<style type="text/css">.tabber{display:none;}<\/style>');
</script>
        </head>
        <body>
        <div id="container">
            <div id="body">
                <h1><br /><strong>Report Generator</strong></h1>
                 <?php date_default_timezone_set('Asia/Dacca');  include 'menu.php';?>  
                    <?php 
                                $preday = date('Y-m-d',strtotime('-190 days')); 
                                $today = date('Y-m-d');
                                include "./chart/libchart/classes/libchart.php";
                                $chart = new VerticalBarChart();
                                $dataSet = new XYDataSet();
                                $query = mysql_query("SELECT DATE_FORMAT(c_date,'%Y-%m-%d') as DATE, 
                                sum(answer_time_duration) as total from data 
                                where DATE_FORMAT(c_date,'%Y-%m-%d') >= '$preday' AND DATE_FORMAT(c_date,'%Y-%m-%d') <= '$today' AND
                                trunc_group IN
                                (0,1,111,211,311,312,511,611,121,221,321,322,421,422,521,621,961,100,101,1211,1212,1311,1312,
                                1511,1611,2011,2211,2511,2611,2911,3011,3611,3711,3911,1811,2311)
                                group by DATE_FORMAT(c_date,'%Y-%m-%d')") or die(mysql_error());
                           while($row = mysql_fetch_array($query)){$dataSet->addPoint(new Point($row['DATE'], round($row['total']/60)));}
                                $chart->setDataSet($dataSet);
                                $chart->render("./chart/generated/chart.png");
                    ?>
                            <img alt="" src="<?php echo base_url();?>/chart/generated/chart.png" style="border: 1px solid gray;"/>
                <div id="dashboard">              
                        <div class="tabber">
                             <div class="tabbertab">
                                  <h2>IGW </h2>
                                  <p>
                                  <table id="datatable" border="1" cellpadding="0" cellspacing="0" width="100%">
                                      <thead>
                                          <tr>
                                              <td>Date</td>
                                              <td>Trunk ID</td>
                                              <td>Trunk Name</td>
                                              <td>Call Attempt Time</td>
                                              <td>Alert Times</td>
                                              <td>Answer Time Duration (MIN)</td>
                                          </tr>
                                      </thead>
                                      <tbody>                                     
                        <?php  $homeigw = $this->db->query("SELECT * FROM data INNER JOIN trunk_info ON trunk_id = trunc_group WHERE trunk_type = 'igw'");
                                         foreach($homeigw->result() as $igww){
                                               echo $igww->id;
                                         }
                                      ?>
                                          </tbody>
                                  </table>
                                  <div style="clear:both;"></div>
                                  </p>
                             </div>
                             <div class="tabbertab">
                                  <h2>ANS - INT</h2>
                                  <p>Tab 2 content.</p>
                             </div>
                             <div class="tabbertab">
                                  <h2>ANS IGW</h2>
                                  <p>Tab 3 content.</p>
                             </div>
                        </div>
                   <!-- END -->             
                    <div style="clear:both;"></div>
                </div>       
                    </div>
                </div>          
                </div>     

        </body>
        </html>

任何有价值的建议将不胜感激。

【问题讨论】:

  • 顺便说一句,数据库相关的操作应该在模型而不是视图中进行,应该是模型 --> 控制器 --> 视图
  • 当我在视图页面中加载模型时,同样的事情正在发生。如果我删除 $this->Dboard_model->hometab_igw(); html 页面结构运行良好。否则页面为空白。
  • 您是否真的从该查询中获取行,可能在 foreach 之前执行 $homeigw->num_rows() 会有所帮助..?
  • 是的。如果我使用过 $homeigw->num_rows();它正在显示行号。还使用了 print_r($homeigw);

标签: php codeigniter loops foreach


【解决方案1】:

如果你在使用 Codeigniter,为什么不使用 codeigniter 的 MVC?你不应该在 View.php 上查询。而是在 Model.php 上做

型号:

 public function MODELFUNC()
    {
    $homeigw = $CI->db->query("SELECT * FROM data INNER JOIN trunk_info ON trunk_id =     trunc_group WHERE trunk_type = 'igw'");
     if ($homeigw->num_rows() > 0 )
        {
    $result = $homeigw->result();
        }

    return $result;
    }

控制器:

public function CONTFUCN()
{
$data['varData'] = $this->MODEL->MODELFUNC();
$this->load->view(<ViewName>, $data);
}

查看:

<?php <tr><th>ID</th></tr>
foreach($varData in varDat)
{
echo "<td>" . $varDat->id ."</td>";
}
?>

【讨论】:

    【解决方案2】:

    在视图页面 $this 可能无法正常工作

    试试这个

    $CI= &get_instance();
    
    <?php  $homeigw = $CI->db->query("SELECT * FROM data INNER JOIN trunk_info ON trunk_id = trunc_group WHERE trunk_type = 'igw'");
            foreach($homeigw->result() as $igww){
                        echo $igww->id;
              }
    

    【讨论】:

    • 不,没有错误。使用 foreach 后页面变空白
    【解决方案3】:

    首先检查您的查询是否返回结果。要检查这一点,您可以输入 if 条件:

    if($homeigw->num_rows() >0) {
        foreach($homeigw->result() as $igww){
              echo $igww->id;
        }
    } else { 
       echo 'empty result set';
    }
    

    【讨论】:

    • 对不起,这不起作用。虽然我得到了行数
    【解决方案4】:

    第一次使用

    print_r($homeigw); 退出;

    检查您的结果,然后相应地使用 foreach 循环。

    【讨论】:

      【解决方案5】:
      <?php
      class plan_model extends CI_Model {
      
          public function __construct()
          {
              $this->load->database();
          }
          public function getevents()
          {
              $json = array();
              $query =$this->db->query("(select a.id,REPLACE(a.interest,'@',',') AS title,a.start,a.end,a.allDay,a.className,a.color from ta_plan a ) union (select b.id,substr(c.name,1,15) AS title,b.start,b.end,b.allDay,b.className,b.color from ta_trips b join ta_city c on b.city_id=c.id order by b.id)");
              echo json_encode($query->result_array());
          }
      
          public function getplandetails($id)
          {
              $query =$this->db->query("SELECT id,city_id,creator_id,plan_desc,standard_activity_id,meeting_address,capacity,start,end,start_time,end_time,title,interest FROM ta_plan where id ='".$id."' ");
              return $query->row_array();   
          }
      
          public function getactivitydetails($id)
          {
              $query =$this->db->query("SELECT id,interest,city_id,start FROM ta_plan where creator_id ='".$id."' ");
              return $query->result_array();   
          }
      
          public function gettripdetails($id)
          {
              $query =$this->db->query("SELECT hotel,hotel_address,city_id,start,end FROM ta_trips where traveller_id ='".$id."' ");
              return $query->result_array();   
          }
      
          public function getprofiledetails($id)
          {
              $query =$this->db->query("SELECT email_id,public_email,facebook_id,public_facebook_id,photo,public_photo,desk_photo,name,public_name,nationality,public_nationality,gender,public_gender,dob,public_dob,marital_status,public_marital_status,home_location,public_home_location,traveller_type,public_traveller_type,traveller_profession,public_traveller_profession,traveller_interest,public_traveller_interest FROM ta_user_profile where id ='".$id."' ");
              return $query->row_array();   
          }
      
          public function gethoteletails($id)
          {
              $query =$this->db->query("SELECT id,name,email_id,location,address,phone,description,facebook_id,photo FROM ta_hotel_profile where id ='".$id."' ");
              return $query->row_array();   
          }
      
          public function getactivitysearch($start,$end)
          {
              if($start!='' && $end!='')
              {
                  $query =$this->db->query("select b.creator_id,a.name as username,a.gender,a.home_location,a.dob,a.desk_photo,a.photo,a.email_id,b.id,b.interest,c.name as cityname,b.start from ta_user_profile a join ta_plan b on a.id=b.creator_id join ta_city c on b.city_id=c.id where b.start >='".$start."' and b.end <='".$end."' ");
              }
              else if($start!='' && $end=='')
              {
                  $query =$this->db->query("select b.creator_id,a.name as username,a.gender,a.home_location,a.dob,a.desk_photo,a.photo,a.email_id,b.id,b.interest,c.name as cityname,b.start from ta_user_profile a join ta_plan b on a.id=b.creator_id join ta_city c on b.city_id=c.id where b.start <='".$start."' and b.end >='".$start."' ");
              }
              else if($start=='' && $end!='')
              {
                  $query =$this->db->query("select b.creator_id,a.name as username,a.gender,a.home_location,a.dob,a.desk_photo,a.photo,a.email_id,b.id,b.interest,c.name as cityname,b.start from ta_user_profile a join ta_plan b on a.id=b.creator_id join ta_city c on b.city_id=c.id where b.start <='".$end."' and b.end >='".$end."' ");
              }
      
             return $query->result_array();
          }
      
          public function get_activity_list($start)
          {
      
             $query =$this->db->query("SELECT id,city_id,creator_id,plan_desc,standard_activity_id,meeting_address,capacity,start,end,start_time,end_time,title FROM ta_plan where start <='".$start."' and end >='".$start."' ");
             return $query->result_array();
          }
      
          public function autocomplete_city($val)
          {
              $query =$this->db->query('select id,country,state,name from ta_city where name LIKE "%'.$val.'%"');
          return $query->result();        
          }
      
          public function get_hotel_list($val)
          {
              $query =$this->db->query('select id,name from ta_hotel_profile where location LIKE "%'.$val.'%"');
          return $query->result_array();        
          }
      
      
          public function get_standard_list($val)
          {
              $query =$this->db->query('select id,title,description,picture from ta_standard_activity where destination_name LIKE "%'.$val.'%"');
          return $query->result_array();        
          }
      
          public function get_hotel_addr($val)
          {
              $query =$this->db->query("select id,name,address from ta_hotel_profile where id='".$val."' ");
          return $query->result_array();        
          }
      
          public function getcityname($val)
          {
              $query =$this->db->query("select name from ta_city where id='".$val."' ");
          return $query->row_array();     
          }
      
          public function getusername($val)
          {
              $query =$this->db->query("select name,id from ta_user_profile where id='".$val."' ");
          return $query->row_array();   
          }
      
          public function get_std_desc($val)
          {
              $query =$this->db->query("select id,description,picture,title from ta_standard_activity where id='".$val."' ");
          return $query->result_array();        
          }
      
      
          public function savetrip($city,$hotelid,$hotel,$hoteladdr,$start,$end,$start_time,$end_time,$id)
          {
                  $insert_data = array(
                  'city_id' => $city,
                  'hotel_id' => $hotelid,
                  'hotel' => $hotel,
                  'hotel_address' => $hotel_addr,
                  'start' => $start,
                  'end' => $end,
                  'start_time'=>$start_time,
                  'end_time'=>$end_time,
                  'traveller_id'=>$id
                  );
                  $this->db->insert('ta_trips', $insert_data);
                  return $this->db->insert_id();
          }
      
          public function save_temp_hotel($hotel,$hoteladdr,$id)
          {
                  $insert_data = array(
                  'hotel_name' => $hotel,
                  'hotel_address' => $hoteladdr,
                  'hotel_id'=>$id
                  );
                  $this->db->insert('ta_hotel_temp', $insert_data);
      
          }
          public function saveactivity($cityid,$stdid,$chk_interest,$title,$description,$start,$end,$start_time,$end_time,$capacity,$flag,$address,$meeting_loc,$id)
          {
      
                  $insert_data = array(
                  'city_id' => $cityid,
                  'standard_activity_id' => $stdid,
                              'interest' => $chk_interest,
                  'title' => $title,
                  'plan_desc' => $description,
                  'start' => $start,
                  'end' => $end,
                  'start_time'=>$start_time,
                  'end_time'=>$end_time,
                              'capacity' => $capacity,
                  'approval_flag' => $flag,
                              'meeting_address' =>$address,
                  'meeting_coordinates'=>$meeting_loc,
                  'creator_id'=>$id
                  );
                  return $this->db->insert('ta_plan', $insert_data);
          }
      }
      ?>
      

      【讨论】:

      【解决方案6】:
      class plan_model extends CI_Model {
      
          public function __construct()
          {
              $this->load->database();
          }
          public function getevents()
          {
              $json = array();
              $query =$this->db->query("(select a.id,REPLACE(a.interest,'@',',') AS title,a.start,a.end,a.allDay,a.className,a.color from ta_plan a ) union (select b.id,substr(c.name,1,15) AS title,b.start,b.end,b.allDay,b.className,b.color from ta_trips b join ta_city c on b.city_id=c.id order by b.id)");
              echo json_encode($query->result_array());
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-04
        • 1970-01-01
        • 2017-05-28
        • 1970-01-01
        • 1970-01-01
        • 2016-02-21
        • 2011-04-08
        • 1970-01-01
        相关资源
        最近更新 更多