Reputation: 3
this is my code
include('connect.php');
$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 !
Upvotes: 1
Views: 3307
Reputation: 72299
Don't use mysql_*
its deprecated, so use mysqli_*
or PDO
. Given example here:-
<?php
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
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 the connection
?>
Upvotes: 1
Reputation: 851
you can call mysql_fetch_assoc() function to do it
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;
}
Upvotes: 0
Reputation: 780949
If you want to get all the results from the query, you need to call mysql_fetch_array
in a loop and push each row onto the 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']);
}
Upvotes: 1
Reputation: 177
Use the below code for your desired output:
<?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>";
?>
Upvotes: -1