Welcome Guest, Not a member yet? Register   Sign In
Random Query
#1

[eluser]Philo01[/eluser]
Hi there!

I'm trying to pull random data from a table, and found the following "solution":

http://www.derekallard.com/blog/post/ord...deigniter/

Code:
$this->db->select('name');
$query = $this->db->get('table');
$shuffled_query = $query->result_array();
shuffle ($shuffled_query);

foreach ($shuffled_query as $row) {
    echo $row['name'] . '<br />';
}

Now when I apply this method on my application, I get the following error:

Quote:A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

My model returns the array to my controller:

Code:
$this->db->where('activated', '1');
$this->db->where('expired', '0');
$ads = $this->db->get('orders');
return shuffle($ads->result_array());

Next, my Controller sends the array to a view:

Code:
foreach($ads as $a){
      // code here
}

When I use this code without the shuffle part it works perfect, only it doesn't select randomly.
When I use the shuffle solution, I get that error.

Anyone who can help me out Smile ?

Kind regards,

Philo
#2

[eluser]CtheB[/eluser]
Sorry i don't use active record in codeigniter so i can't help you.

It is much easier to do it like this:

$query = $this->db->query("SELECT * FROM orders where activated = 1 AND expired = 0 ORDER BY rand() ");
return $query->result_array();
#3

[eluser]Philo01[/eluser]
[quote author="CtheB" date="1260490524"]Sorry i don't use active record in codeigniter so i can't help you.

It is much easier to do it like this:

$query = $this->db->query("SELECT * FROM orders where activated = 1 AND expired = 0 ORDER BY rand() ");
return $query->result_array();[/quote]

Thanks mate! Smile
#4

[eluser]jedd[/eluser]
I believe (but have not tested or confirmed) that it is preferable, for performance reasons, to query the database on the number of rows in the table, use a local PHP random function against that figure, and then extract that specific record from the database.
#5

[eluser]WhitecastlePT[/eluser]
Hello, here's an example with active records: Works like a charm Wink

Code:
function getAllFotos()
    {
       $data = array();
       $this->db->select();
       $this->db->from('foto_tbl');  
       $this->db->where('isthumb',1);     /* <-- You can remove this */          
       $query = $this->db->get();            
       if($query->num_rows() > 0)
           {
               foreach ($query->result() as $row)
                {
                    $data[] = $row;                    
                }
                srand((float)microtime()*1000000); /* example from suffle function in PHP manual, values can be altered!*/
                shuffle($data);
                return $data;
           }
    }




Theme © iAndrew 2016 - Forum software by © MyBB