php - How can I convert record set from database to array?

799

How can I convert record set from database to array? It has 1 table named:tblproduct, with the following schema:

 product_id | product_name | product_desc | product_price | product_img

When I select data from the database I would like an array in the following format:

$product_array = array(
  "105" => array('product_id' => '105', 'product_name' => 'Blackberry 8900',
                 'product_desc' => '', 'product_price' => '1150.00',
                 'product_img' => 'products/product5.jpg'),
  "106" => array('product_id' => '106', 'product_name' => 'Headphone with mic',
                 'product_desc' => '', 'product_price'=>'148.85', 
                 'product_img' => 'products/product8.jpg')
);

Best regards

644

Answer

Solution:

Assuming you are using MySQL (You didn't specify your DBMS) and have a line like:

$result = mysql_query('SELECT * FROM `tblproduct`');

You can use:

while($row = mysql_fetch_assoc($result))
    $product_array[$row['product_id']] = $row;

People are also looking for solutions to the problem: PHP DateTime : get current week/month/year interval (start-end) compared with the previous year

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.