Jump to content

pls help me with foreach with functions and sql queries


ibinod

Recommended Posts

firstly my database structure is like this

main_category table contains id and title column

sub_category table also contains id and title column

& category table contains various feilds including main_cat and sub_cat feild

 

and i have created those function

 

  function results_array($result)
{
  $result_array = array();
	for ($i=0; $row = mysql_fetch_array($result) ; $i++)
	{
	   $result_array[$i] = $row; 
	}

	return $result_array;
}


//function to get main category tables array
function main_cats()
{
$connect = connect_db(); //connects to db
$query = "SELECT * FROM main_category ORDER by id DESC";
$result = mysql_query($query);
if(mysql_num_rows($result) == 0)
{
	return false;
}
$result = results_array($result); //turns the results into array using for loop function
return $result;
}

function sub_cats()
{
$connect = connect_db(); //connects to db
$query = "SELECT * FROM sub_category ORDER by id DESC";
$result = mysql_query($query);
if(mysql_num_rows($result) == 0)
{
	return false;
}
$result = results_array($result); //turns the results into array using for loop function
return $result;
}

 

now what i want to do is i want to create a function similar to above that outputs the results as an array

$main_cats = main_cats();
$sub_cats = sub_cats();

foreach ($main_cats as $main_cat):
echo $main_cat['title']."<br />";

foreach ($sub_cats as $sub_cat):
echo $sub_cat['title']."<br />";

	$GetCat = mysql_query("SELECT * FROM cats WHERE main_cat='".$main_cat['id']."' AND sub_cat='".$sub_cat['id']."' ORDER BY title ASC");
	while($GSc = mysql_fetch_array($GetCat)) 
	{
		echo $GSc['title'];
	}



endforeach;

endforeach;

the above code gives me wt i want but i want to put it inside a function and return results as an array

 

pls help me

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.