如何从sql表创建关联数组

时间:2016-02-12 07:33:40

标签: php sql

这是我的代码

include('connect.php');
$prod = mysql_query("SELECT * FROM products");
$all = mysql_fetch_array($prod);

我不会创建像这样的关联数组

$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']),
);
你可以帮帮我吗?谢谢!

4 个答案:

答案 0 :(得分:1)

如果要从查询中获取所有结果,则需要在循环中调用mysql_fetch_array并将每行推送到数组上。

$product_array = array();
while ($all = mysql_fetch_array($prod)) {
    $product_array[] = array('product_id'=>$all['pid'], 'product_name'=>$all['pname'],'product_desc'=>$all['pdesc'], 'product_price'=>$all['pprice'], 'product_img'=>$all['pimage']);
}

答案 1 :(得分:1)

请勿使用已弃用的mysql_*,因此请使用mysqli_*PDO。举个例子: -

<?php
error_reporting(E_ALL); // check all errors
ini_set('display_errors',1); // display errors
$conn = mysqli_conncet('host name','user name','password','database name');//database connection code
$product_data = array(); // create an empty array
if($conn){
 $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
}else{

  echo mysqli_connect_error(); // show what problem occur in database connectivity
}
mysqli_close($conn); // close connection
?>

答案 2 :(得分:0)

你可以调用mysql_fetch_assoc()函数来做到这一点

include('connect.php');
$sql = mysql_query("SELECT product_id,
                            product_name,
                            product_desc,
                            product_price,
                            product_img
                      FROM products");
$prod = mysql_query($sql);
while ($r = mysql_fetch_assoc($prod)){
    $product_array[] = $r;
}

答案 3 :(得分:-1)

使用以下代码获得所需的输出:

<?php
include('connect.php');
$prod = mysql_query("SELECT * FROM products");
$all = mysql_fetch_array($prod);
$allCount   =   count($all);
$product_array  =   array();

if($allCount)
{
    for($i=0; $i<$allCount; $i++)
    {
      $product_array[$i]['product_id']   =   $all[$i]['pid'];
      $product_array[$i]['product_name']  =   $all[$i]['pname'];
      $product_array[$i]['product_desc']  =   $all[$i]['pdesc'];
      $product_array[$i]['product_price'] =   $all[$i]['pprice'];
      $product_array[$i]['product_img']   =   $all[$i]['pimage'];   
    }
}

echo "<pre>";
print_r($product_array);
echo "</pre>";
?>