I'm new to OOP php and I am trying to load objects into an array. I followed the syntax I found here and it works but only for the first object :sad:
Here is the code i am using for the class
class category {
// Variables
var $id, $name, $description, $dept_id, $parent_id;
//Function to pull Category Details
function get_category_details($cat_id){
if($cat_id == 0 or is_nan($cat_id)){return null;}
$cat = mysql_query("SELECT * FROM tbl_categories WHERE cat_id = " . $cat_id) or trigger_error("Could not get Categories" . mysql_error());
if(mysql_num_rows($cat) < 1){
return null;
}
else{
while($row = mysql_fetch_array($cat)){
$this->id = $row["cat_id"];
$this->name = $row["cat_name"];
$this->description = $row["cat_desc"];
$this->dept_id = $row["cat_dept_id"];
$this->parent_id = $row["cat_parent_cat_id"];
}
mysql_free_result($cat);
return $this;
}
}
//Function to get sub-categories of a category, returns an array of the categories
function get_sub_categories($cat_id){
$cats = mysql_query("SELECT * FROM tbl_categories WHERE cat_parent_cat_id = " . $cat_id) or trigger_error("Could not get Categories" . mysql_error());
if(mysql_num_rows($cats) < 1){
return null;
}
else{
$subCats = array();
while($row = mysql_fetch_array($cats)){
$tmp_cat = new category();
$tmp_cat = $this->get_category_details($row["cat_id"]);
echo $tmp_cat->name;
$subCats[] = $tmp_cat;
}
mysql_free_result($cats);
return $subCats;
}
}
}
And here is the code I am using to print the array
<?php
include_once("category.php");
//This code generates the left nav columns
$cat = new category();
$cat = $cat->get_category_details(1);
$cats= $cat->get_sub_categories(1);
echo "<h1>" . $cat->name . "(" . count($cats) . ")</h1>";
foreach ($cats as $c) {
$tmpCat = new category();
$tmpCat =& $c;
echo "Temp:" . $tmpCat->description . "<br />";
}
?>
And here is what I am getting when I run it:
HalterSleevelessShort Sleeves3/4 SleevesLong SleevesJackets & Blazers
Tops(6)
Temp:Halter
Temp:
Temp:
Temp:
Temp:
Temp:
Please help! Why is it only storing the first object? I've tried using array_push() and I have printed out the category objects right before they are loaded into the array. So the problem is almost definitely something to do with how the array is loaded.
I'm pulling my hair out!!!