how to create associative array from sql table

this is my code

$prod = mysql_query("SELECT * FROM products");
$all = mysql_fetch_array($prod);

and i wont create associative array look like this

$product_array = array(
   '1' =>array('product_id'=>$all['pid'], 'product_name'=>$all['pname'],'product_desc'=>$all['pdesc'], 'product_price'=>$all['pprice'], 'product_img'=>$all['pimage']),

can you help me ? thanks !


  • Don't use mysql_* its deprecated, so use mysqli_* or PDO. Given example here:-

    error_reporting(E_ALL); // check all errors
    ini_set('display_errors',1); // display errors
    $conn = mysqli_connect('host name','user name','password','database name');//database connection code
    $product_data = array(); // create an empty array
     $prod = mysqli_query($conn,"SELECT * FROM products");
        while ($all = mysql_fetch_array($prod)) {
            $product_data[] = array('product_id'=>$all['pid'], 'product_name'=>$all['pname'],'product_desc'=>$all['pdesc'], 'product_price'=>$all['pprice'], 'product_img'=>$all['pimage']); // assignment
        echo "<pre/>";print_r($product_data); // print product_data array
      echo mysqli_connect_error(); // show what problem occur in database connectivity
    mysqli_close($conn); // close the connection