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
         } 
5
  • try mysql_fetch_assoc($q) instead mysql_fetch_array($q); Commented Dec 29, 2013 at 7: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. So do a while or for loop while using it to get all the rows. Commented Dec 29, 2013 at 7:43
  • @AwladLiton That won't help, instead of returning a numerically indexed array for each row, it will return an associative one. Commented Dec 29, 2013 at 7: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 Commented Dec 29, 2013 at 7:48
  • 1
    note about ORDER BY RAND() performance Commented Dec 29, 2013 at 7:49

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, exactly my thoughts. ++
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);

1 Comment

How do you figure this helps? You are just assigning a row to a defined index in an array.
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);

Comments

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 />";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.