0

I am trying to get the data from database in one single array but I was unsuccessful doing that. What I have tried is -

$q = mysql_query("SELECT*FROM meaning ORDER BY RAND() LIMIT 7");
$gt = mysql_fetch_array($q);
var_dump($gt);

This query fetches only one row. What I want is that this query should fetch random 7 rows and come back in one array as data like -

array(4) { [0]=> row_0
           [1]=> row_1
           [2]=> row_2
           [3]=> row_3
           [4]=> row_4
           [5]=> row_5
           [6]=> row_6
         } 
Nishant Ghodke
  • 923
  • 1
  • 12
  • 21
  • try mysql_fetch_assoc($q) instead mysql_fetch_array($q); – Awlad Liton Dec 29 '13 at 07:40
  • 3
    First, `mysql_` is deprecated, please switch to `mysqli_` or `PDO`. ^^ Secondly, you can, but you have to create a loop. From the function [`mysql_fetch_array`](http://www.php.net/manual/en/function.mysql-fetch-array.php). So do a `while` or `for` loop while using it to get all the rows. – Jon Dec 29 '13 at 07:43
  • @AwladLiton That won't help, instead of returning a numerically indexed array for each row, it will return an associative one. – Jon Dec 29 '13 at 07:45
  • Actually, if you use mysqli_fetch_array the returned array has characteristics numeric and associative arrays. Not certain if mysql_fetch_array does, though – David Wilkins Dec 29 '13 at 07:48
  • 1
    [note about ORDER BY RAND() performance](http://stackoverflow.com/questions/14330798/mysql-order-by-rand-performance-issue-and-solution) – Jan Turoň Dec 29 '13 at 07:49

4 Answers4

8

There is no function in the mysql extension that does what you want. All the mysql_fetch_XXX functions read just one row at a time. To get everything, you have to use a loop:

$gt = array();
while ($row = mysql_fetch_assoc($q)) {
    $gt[] = $row;
}
var_dump($gt);

If you convert to the PDO extension, it has the method PDO::fetchAll that does what you want.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Hope this may helps you,

 $q = mysql_query("SELECT * FROM meaning ORDER BY RAND() LIMIT 7");
 while($gt = mysql_fetch_assoc($q)){
   $myarray[] =  $gt;
 }   
 var_dump($myarray);
Krish R
  • 22,583
  • 7
  • 50
  • 59
  • 1
    How do you figure this helps? You are just assigning a row to a defined index in an array. – Jon Dec 29 '13 at 07:44
0

Try this:

$q = mysql_query("SELECT * FROM meaning ORDER BY RAND() LIMIT 7");
$i = 0;
$myarray[]='';

while($gt = mysql_fetch_assoc($q))
{
  $myarray[$i] = $gt;
  $i++;
}

var_dump($myarray);
AyB
  • 11,609
  • 4
  • 32
  • 47
0

mysql_fetch_array returns the first row in a MySQL Resource in the form of an associative array. Fetches a result row as an associative array, a numeric array, or both.
You need to use loop to get all the records.

$q = mysql_query("SELECT * FROM meaning ORDER BY RAND() LIMIT 7");

while ($row = mysql_fetch_array($q)) {
    echo $row["title"]."<br />";
}
RaviRokkam
  • 789
  • 9
  • 16