0

how to get all data in single array without using while statement. here is some code but its not working good.. any idea about whole query result in sigle assoc array.. any idea??

$data=array();
$sql = "SELECT `Name`, `Title`, `Version`, `Date`, `Cover`, `Content` FROM dict";
$result=mysql_query($sql);

while($data[]=mysql_fetch_assoc($result))
{
$data[]=mysql_fetch_assoc($result);
}
print_r($data);
3
  • What is not working good? Alternatively you can wrap it into a function of it's own and return the whole array or switch to some other database access library like PDO that supports such an operation out of the box.
    – hakre
    Jan 29, 2012 at 19:20
  • its returning such output while i have only 2 records <br> Array ( [0] => Array ( [Name] => Test [Title] => Test [Version] => 4 [Date] => 2012:01:29 12:25:44 [Cover] => localhost/mag/uploaded/imagesmagazine-4.jpg [Content] => localhost/mag/uploaded/pdfmagazine-4.pdf ) [1] => Array ( [Name] => Test [Title] => Test [Version] => 4 [Date] => 2012:01:29 12:25:44 [Cover] => localhost/mag/uploaded/imagesmagazine-4.jpg [Content] => localhost/mag/uploaded/pdfmagazine-4.pdf ) [2] => )
    – Natasha
    Jan 29, 2012 at 19:21
  • You fetch two rows per while iteration. And the last elment of $data will be FALSE. See the answers and how they do it differently.
    – hakre
    Jan 29, 2012 at 19:22

3 Answers 3

3

You can wrap it into a function of it's own (and correct the error) so you can't mis-type it any longer:

mysql_fetch_assoc_all($result)
{
    $data = array();
    while  ($row = mysql_fetch_assoc($result))
    {
        $data[] = $row;
    }
    return $data;
}

Usage:

$sql = "SELECT `Name`, `Title`, `Version`, `Date`, `Cover`, `Content` FROM dict";
$result = mysql_query($sql);
$data = mysql_fetch_assoc_all($result);

Take care that $result must be a valid result.

0
0

The reason why it's not working is how you do your loop.

while($row = mysql_fetch_assoc($result))
{
    $data[] = $row;
}

Then you have an array of associative arrays in $data.

I'm not aware of any "single-line" solution. Although you can of course wrap all this in a function as hakre suggests.

0

Little bit late, but "single line" could be:

while($data[] = mysql_fetch_assoc($result));

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.