php - 将 mysql_query 结果传递给 foreach

标签 php mysql sql codeigniter loops

我使用以下代码来获取 Facebook 好友的用户列表,并根据应用程序数据库中的用户进行检查。此代码将返回应用程序的用户,即该用户的 Facebook 好友。

     $friends_set = '(';
             foreach($friends["data"] as $value) {
                 $friends_set .= $value['id'].','; 
             }
             $new_set = preg_replace('/,$/',')',$friends_set);
               $res = mysql_query("SELECT * from user AS u, upload AS up WHERE u.fb_id IN $new_set AND u.fb_id=up.user_id") or die(mysql_error());

    while($row = mysql_fetch_array($res)) {

        echo $row['fb_id']. "". $row['first_name'];
        echo "<br>"; 

      }

$data['top_friends']=$res;
$this->load->view('myview');

这段代码有效。它位于我的 codeigniter 应用程序的 Controller 中,并且成功地将正确的数据回显到页面上。

但是现在我需要在我的 View 中的每个语句中打印查询结果,如下所示:

<?php foreach ($top_friends as $me) : ?>

                    <div >

                    <p><?php echo $me['first_name']; ?></p>

                     <?php endforeach; ?>

但是,当我尝试使用 foreach 在 View 中获取查询结果时,它不起作用。

我该如何解决这个问题?

最佳答案

您可以尝试使用 codeignitor 方式,创建一个模型函数,例如 get_top_friends ,我假设您传递一个逗号分隔的字符串作为参数,例如 $fb_id = '45,65,78,89' 。假设 facebook_model 是模型的名称:

class Facebook_model extends CI_Model{
     //other functions and constrcutor here

    //function to get the top friends
     function get_top_friends($fb_id){
       $fbId = explode(",",$fb_id)
       $this->db->select('*');
       $this->db->where_in('fb_id',$fbId);
       $this->db->order_by('points','desc');
       $this->db->limit(10);
       $query = $this->db->get('user');
       if ($query->num_rows() < 1) return FALSE;
       return $query->result_array();
     }
}

并对代码进行如下更改:

 $friends_set = '';
     foreach($friends["data"] as $value) {
         $friends_set .= $value['id'].','; 
     }
     $new_set = preg_replace('/,$/',')',$friends_set);
     $res = $this->facebook_model->get_top_friends($new_set);
     $data['top_friends']=$res;
     $this->load->view('myview',$data);

现在您可以尝试

foreach ($top_friends as $me){
  echo $me['first_name'];
}

[为用户更新]

如果您想按照问题中的方式进行操作:那么请尝试,

$result = array();
while($row = mysql_fetch_array($res)) {
        $result[] = $row;  
}
$data['top_friends']=$result;
$this->load->view('myview',$data);//pass data to view

关于php - 将 mysql_query 结果传递给 foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21366364/

相关文章:

php - CakePHP的列表问题

javascript - 无法将文本区域值传递到我的表单

php - 数据表 : How to make a page load faster?

python - web.py select 不返回结果,但该列表的长度确实返回(sql promt 中的手动查询也返回结果)

MySQL 使用 char_length() 检查一系列字符未给出结果

sql - 使用 SQL 查询的数据挖掘操​​作(模糊先验算法) - 使用 SQL 对其进行编码

php - 计算受 plpgsql 函数影响的行数

php - 从上传查询中查看特定 ID

mysql - 选择按最低 second_field 过滤具有相同字段的行的条目

sql - 使用 txid 获取最新的未处理、更新的行