GETTING SQL RESULT INTO AN ARRAY

Garry Winogrand

Total Post:24

Points:168
Posted by  Garry Winogrand
JSON 
 1201  View(s)
Ratings:
Rate this:
Hi Developers!

I'm trying to get a MySQL result like "SELECT * FROM sales" into an array that looks like this:

$data = array( 
         array('Date', 'Sales'),  
         array('June 25', 12.25),  
         array('June 26', 8.00) 
 );

I tried it with a while loop but it didn't work. How can i do this?

Thanks in advance. 
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: Getting SQL result into an array

    Hi Garry!


    Try this

    $query = "SELECT * FROM sales";
    $data = array();
    $data[] =array('Date', 'Sales');

    if ($result = $mysqli->query($query)) 
    {        
        while ($line = $result->fetch_assoc()) 
        {        
            // line contain an associative array with "Date" and "Sales"  
            $data[] = array($line['Date'], $line['Sales']);
        }
    }

    $result->free();

    I hope it helpful for you!

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!