I have two tables.
The finalists table which lists the finalists with fields such as ID, Name. The Votes table which stores the votes for those finalists. One row in the vote tables where the field "confirmed" is yes means one vote.
To get the number of votes for a particular finalist I run
$this->db->where('finalist_id', $finalist_id);
$this->db->where('confirmed', 'yes');
$query = $this->db->get('votes');
return $query->num_rows();
And that gets me the number of rows.(votes)
Now what I want to do is loop through my finalists and list their name, their ID and their number of votes but I am struggling to write the code in my controller.
My controller :
$this->load->database();
$query = $this->db->get('finalists');
$data['finalists'] = $query->result_array();
$this->db->where('finalist_id', $finalist->id);
$this->db->where('confirmed', 'yes');
$query = $this->db->get('votes')
$data['votes'] = $query->result_array();
$this->template
->build('admin/listing', $data);
My view:
<?php foreach ($finalists as $finalist): ?>
<li>ID:<?php echo $finalist['id'] ?>, Name:<?php echo $finalist['name'] ?>, votes:<?php echo $finalist['votes'] ?></li>
<?php endforeach ?>
SO what I am trying to achieve is to add the key vote and its result to the array $finalists - obviously to the right one, and I can't get my head around how to do that.
I suppose I should loop through the finalists and somehow insert the result of the query for that particular finalist.
Any help would be appreciated.
JOIN
and theSUM()
function in conjunction withGROUP BY
. This can allow you to get your entire result set in a single query. Though I don't use codeigniter, I am sure there is documentation out there on how to do this. – Mike Brant Aug 6 '13 at 0:45SELECT f.id, f.name, COUNT(v.confirmed) AS votes FROM finalists AS f INNER JOIN votes AS v on f.id = v.finalist_id WHERE v.confirmed = 'yes' GROUP BY f.id
should get you started. – Mike Brant Aug 6 '13 at 1:34