• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
handling query results with codeigniter

#1
[eluser]joeizang[/eluser]
hi y'all,

I have another question that I need help with.

Now I know that when you query the database with CI activerecord, it usually returns multidimensional array's if there is more than one row returned. I want to populate list items on my html page with titles from a database. with my code all i get returned is one title. using php functions like var_dump etc I see that the result is multidimensional. what do I do? here is a sample of my code:


<ul>
<li><a href="#" id="article9">text1</a></li>
<li><a href="#" id="article10">Ttext2</a></li>
<li><a href="#" id="article11">Text3</a></li>
</ul>

&lt;?php
function gettitle3()
{
$this->db->select('articletitle');
$this->db->from('articles');
$this->db->where('articlecategory',2);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$Q = $query->result_array();
foreach($Q as $value){
return $value;
}
}
}

$answer = $this->articles->gettitle3();
if($answer){
$data['heads'] = $answer;
}
$this->load->view('dummy_view',$data);

foreach($heads as $tails)
{
//var_dump($t);
//print_r($t)."<br />";
echo $tails['articletitle'];
// var_dump($tails);
}

?&gt;

#2
[eluser]BrianDHall[/eluser]
[quote author="joeizang" date="1254943868"]
Code:
function gettitle3()
{
$this->db->select('articletitle');
$this->db->from('articles');
$this->db->where('articlecategory',2);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$Q = $query->result_array();
foreach($Q as $value){
return $value;
  }
}
}
[/quote]

Your problem is your foreach. What is happening is the foreach gets one of the values in the $Q array and puts it into $value, then you call return - that breaks for the foreach loop and ends the function.

Doing it this way will ensure you never get more than the first result. Replace "return $value;" with "echo $value;" to see if it works.

#3
[eluser]joeizang[/eluser]
Thanx BrainDHall,

Your explanation was spot-on. But rather than echo, I did the following to the foreach and it worked beautifully:

&lt;?php

function gettitle3()
{
$this->db->select('articletitle');
$this->db->from('articles');
$this->db->where('articlecategory',2);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$Q = $query->result_array();
foreach($Q as $value){
$data[] = $value;
}
return $data;
}
}
?&gt;
Thanx again,


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.