Welcome Guest, Not a member yet? Register   Sign In
in one foreach call second foreach!
#1

[eluser]daka[/eluser]
How is possible to call in foreach again foreach loop?
Hier is the deal:
I have photos table and I call it like this:
in controller:
Code:
$query_not_voted = "SELECT * FROM photos WHERE p_id NOT IN (SELECT distinct p_id FROM p_votes where u_id = ".$this->session->userdata('u_id').") LIMIT ".$segment_url.", ".$config['per_page'];
$data['myphotos'] = $this->db->query($query_not_voted);
if(IS_AJAX){
    $this->load->view('v_members_ajax', $data);
}else{
    $data['main_content'] = 'v_members';
    $this->load->view('includes/template', $data);
}
view:
Code:
foreach ($myphotos->result() as $myphoto){
echo $myphoto->p_small;
}
So now I need to call sql statment in that loop to get people that voted on that photo!
Hier is sql statment:
Code:
SELECT * FROM users WHERE u_id IN (SELECT u_id FROM p_votes WHERE p_id = 'every time in that loop different')

hier is my database:
Code:
CREATE TABLE IF NOT EXISTS `users` (
  `u_id` int(10) unsigned NOT NULL auto_increment,
  `fb_id` varchar(255),
  `fb_url` varchar(255),
  `email` varchar(100),
  `username` varchar(100),
  `name` varchar(100),
  `lastname` varchar(100),
  `mini_pic_fb` varchar(255),
  `mini_pic` varchar(255),
  `country` varchar(100),
  `place` varchar(100),
  `address` varchar(100),
  `nr` int(10),
  `postcode` varchar(10),
  `pass` varchar(35),
  `active` varchar(35),
  `activation_code` varchar(42),
  PRIMARY KEY  (`u_id`),
  UNIQUE KEY `email` (`email`),
  UNIQUE KEY `username` (`username`),
  UNIQUE KEY `fb_id` (`fb_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=229 ;


CREATE TABLE IF NOT EXISTS `photos` (
  `p_id` bigint(20) unsigned NOT NULL auto_increment,
  `u_id` bigint(20) unsigned NOT NULL default '0',
  `p_date` datetime NOT NULL default '0000-00-00 00:00:00',
  `p_content` longtext NOT NULL,
  `p_title` text NOT NULL,
  `p_photo` text NOT NULL,
  `p_small` text NOT NULL,
  `p_thumb` text NOT NULL,
  `p_up` bigint(20),
  `p_down` bigint(20),
  PRIMARY KEY  (`p_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=229 ;

CREATE TABLE IF NOT EXISTS `p_votes` (
  `pv_id` bigint(20) unsigned NOT NULL auto_increment,
  `u_id` bigint(20) unsigned NOT NULL,
  `p_id` bigint(20) unsigned NOT NULL,
  `pv_date` datetime NOT NULL default '0000-00-00 00:00:00',
  `pv_ip` varchar(200) NOT NULL,
  PRIMARY KEY  (`pv_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=229 ;
#2

[eluser]smilie[/eluser]
Yes it is possible, simply do it :-)

Shorthand example (not a real one, but to give you idea):

Code:
$db->select('user_id')->from('users');
$q = $db->get();
$r = $q->result_array();

foreach($r as $key=>$val)
{
    $db->select('comments')->from('comments')->where('comments_user_id',$val['user_id']);
    $q_1 = $db->get();
    $r_1 = $q_1->result_array();
    
    # Second foreach
    foreach($r_1 as $key2=>$val2)
    {
       $db->select('something')->from('somwhere')->where('comm_text',$val2['comments']);
       $q_2 = $db->get();
       $r_2 = $q_2->result_array();
     }
}

Cheers,
Smilie
#3

[eluser]daka[/eluser]
if someone could give live tutorial or post hier the whole thing with model controller and viewer.
tnx.
#4

[eluser]smilie[/eluser]
I do not mean to be rude or anything - but - why?

I mean, there are lot of experienced CI guys for hire (per hour / project).
This is not really that difficult to do, so - please do try it yourself.

Cheers,
Smilie
#5

[eluser]daka[/eluser]
Ok I tryed and for some part it's working, but there is very strange thing, on the first page it doesn't show result and on the other pagination links it shows result, lets see my codes:

Code:
function index()
    {
        
        $this->load->helper('form');
        $this->load->library('pagination');
        //$config['permitted_uri_chars'] = '0-9';
        $config['base_url'] = base_url().'member/index';
        $config['per_page'] = 5;
        $config['num_links'] = 10;
        $query_not_voted_rows = "SELECT p_id FROM photos WHERE p_id NOT IN (SELECT distinct p_id FROM p_votes where u_id = ".$this->session->userdata('u_id').")";
        $config['total_rows'] = $this->db->query($query_not_voted_rows)->num_rows();
        $config['full_tag_open'] = '<div id="pagination">';
        $config['full_tag_close'] = '</div>';
        $this->pagination->initialize($config);
        if($this->uri->segment(3) == '')
        {
            $segment_url = 0;
        }else{
            if(!is_numeric($this->uri->segment(3))){
            redirect('404');
            }else{
            $segment_url = $this->uri->segment(3);
            }
        }
        
        $data['facebook'] = array(
            'user'        => $this->facebook_connect->user,
            'user_id'    => $this->facebook_connect->user_id
        );
        $query_voted = "select * from photos p inner join p_votes v on (p.p_id = v.p_id and v.u_id = ".$this->session->userdata('u_id').") ORDER BY pv_date DESC LIMIT 0, 5";
        //SELECT * FROM photos WHERE p_id IN (SELECT distinct p_id FROM p_votes where u_id = ".$this->session->userdata('u_id')." ORDER BY pv_date) LIMIT 0, 5
        //
        $query_not_voted = "SELECT * FROM photos WHERE p_id NOT IN (SELECT distinct p_id FROM p_votes where u_id = ".$this->session->userdata('u_id').") LIMIT ".$this->db->escape_str($segment_url).", ".$config['per_page'];
        $q = $this->db->query($query_not_voted);
        $data['myphotos'] = $q->result_array();
        //var_dump($data['myphotos']);

        foreach($data['myphotos'] as $key=>$val)
        {
            $query_g = "SELECT * FROM users WHERE u_id = (SELECT u_id FROM p_votes WHERE p_id = ".$val['p_id'].")";
            $q_2 = $this->db->query($query_g);
            $data['allvotes'] = $q_2->result_array();
            
            $query_u = "SELECT * FROM users WHERE u_id = ".$val['u_id']." LIMIT 0, 5";
            $q_1 = $this->db->query($query_u);
            $data['author'] = $q_1->result_array();
            

        }
        
        $data['voted'] = $this->db->query($query_voted);
        if(IS_AJAX){
            $this->load->view('v_members_ajax', $data);
        }else{
            $data['main_content'] = 'v_members';
            $this->load->view('includes/template', $data);
        }
    }

an view is:
Code:
foreach($author as $keyas => $row){
                            echo '< href="'.base_url().'clanovi/clan/'.$row['u_id'].'">'.$row['name'].' '.$row['lastname'].'</>';
                        }
this works fine, but next thing shows array of 0.

Code:
foreach($allvotes as $key => $row){
                            echo ' < href="'.base_url().'clanovi/clan/'.$row['u_id'].'">';
                            echo $row['name'].' '.$row['lastname'].'</> | ';
                        }
So on the first page it gives me no results (there are results nad it shows up in controller with test var_dump()), but in view does not. But if I click on pagination links, then it shows up. This is weird, I don't get it!
#6

[eluser]daka[/eluser]
Someone please...I will pay for this solution...becouse it drives me crasy!!!!
#7

[eluser]daka[/eluser]
This is how I did it....but breaked the rulle of MVC!!!
hier is my controller:
Code:
$query_not_voted = "SELECT * FROM photos"
$q = $this->db->query($query_not_voted);
$data['myphotos'] = $q->result_array();

viewer:
foreach ($myphotos->result() as $myphoto){

$query = "SELECT * FROM users WHERE u_id IN (SELECT u_id FROM p_votes
WHERE p_id = ".$myphoto->p_id.")";
$voters = $this->db->query($query)->result();
?&gt;

< href="&lt;?php echo base_url().$myphoto->p_small; ?&gt;" class="preview"
title="&lt;?php echo base_url().$myphoto->p_title; ?&gt;"><img >p_thumb; ?&gt;" /></>
&lt;?php
                               //all people who voted on this photo
(it is inside of loop)
                                         foreach($voters as $row){
                                                       echo ' <a >u_id.'">';
                                                       echo $row->name.' '.$row->lastname.'</a> | ';
                                               }

}


So this is working version! but the problem is that I call querys in
view (breaking MVC) and I want to do this right!
I hope this can give you better picture!
#8

[eluser]Nick_MyShuitings[/eluser]
This is the Purely MCV way of doing it. Loop through each photo from the result set in your controller, and get the list of the voters for each photo and append it to the photo object/array.

This really is pretty basic logic, which makes me think you were over-thinking it.

Steps:
1) get the photos
2) loop the photos and get the voters for each
3) send to view
4) loop the photos echoing the photo info
5) loop the voters echoing the user info

Controller:
Code:
$this->load->model('pictures_model');

$myphotos = $this->pictures_model->getpics();

foreach ($myphotos as $photo) {
  $voters = $this->pictures_model->getvoters($photo->p_id);
  $photo->voters = $voters;
  $this->data['photos'][] = $photo;
}

$this->load->view('photo_view', $this->data);

Model:
Code:
function getpics() {
  return $this->db->get('photos')->result();
}
function getvoters($p_id) {
  $query = "SELECT * FROM users WHERE u_id IN (SELECT u_id FROM p_votes WHERE p_id = ".$p_id")";
  return $this->db->query($query)->result();
}

View:
Code:
&lt;? foreach ($photos as $photo): ?&gt;
  &lt;?= $photo->p_title;?&gt;
  &lt;?= $photo->p_photo;?&gt;
  &lt;?= $photo->p_small;?&gt;
  &lt;?= $photo->p_thumb;?&gt;
  &lt;? foreach ($photo->voters as $voter):?&gt;
    &lt;?= $voter->name;?&gt;
    &lt;?= $voter->username;?&gt;
  &lt;? endforeach;?&gt;
&lt;? endforeach; ?&gt;

[EDIT] I'll take my payment in the form of a comic drawn by you about anything you feel like, no limits on length, color, talent etc... hehe...




Theme © iAndrew 2016 - Forum software by © MyBB