function build_list($id=0,$collapsed="") //return an array with the categories ordered by position
{
$RootPos = "";
$this->c_list = array();
if($id != 0){
$this_category = $this->fetch($id);
$positions = explode(">",$this_category['position']);
$RootPos = $positions[0];
}
// lets fetch the root categories
$sql = "SELECT *
FROM ".$this->table_name."
WHERE position RLIKE '^([0-9]+>){1,1}$' AND c_group = '".$this->Group."'
ORDER BY c_name";
$res = mysql_query($sql) or die(trigger_error("<br><storng><u>MySQL Error:</u></strong><br>".mysql_error()."<br><br><storng><u>Query Used:</u></strong><br>".$sql."<br><br><storng><u>Info:</u></strong><br>",E_USER_ERROR));
while($root = mysql_fetch_array($res)){
$root["prefix"] = $this->get_prefix($root['position']);
$this->c_list[$root['id']] = $root;
if($RootPos == $root['id'] AND $id != 0 AND $collapsed != ""){
$this->list_by_id($id);
continue;
}else{
// lets check if there is sub-categories
if($collapsed == "" AND $id==0){
$has_children = $this->has_children($root['position']);
if($has_children == TRUE) $this->get_children($root['position'],0);
}}}
return $this->c_list;
}
// He is the Author of the code...
Categories Class
Author: Shadi Ali
Now I want to just return the Categories and Sub Categories from the above code.
function browse() {
$categories = new categories;
$categories_list = $categories->build_list();
foreach($categories_list as $c)
{
return $c->$id;
}
}
The above code is not working.... can anyone help me out.
Here are two problems with the browse() function:
The return statement is inside the foreach loop. The statement will return one value for one of the items in the $categories-list (at most), and not continue to loop over the rest of the $categories-list.
The $id variable is never declared or initialised in return $c->$id, perhaps you meant to use $c['id'] or $c->id
Related
I am taking data from many tables. I want to display many objects in different places. I got the data from data base, but I want to put the data into an array for useful purpose, but it's not working.
This my controller code:
public function compare_by_business_sectors() {
//print_r($this->input->post());exit;
if ($this->input->post())
{
$solution_array = array();
//print_r (json_encode($business_sectors)); exit;
$business_sectors=$this->home_model->compare_business_sectors_data($this->input->post());
$tab_child_id = "";
$id="";
foreach ($business_sectors as $key=>$sectors) {
$solution_array[1]=$sectors->solution_name;
$solution_array[2]=$sectors->description;
$solution_array[3]=$sectors->vendor_name;
$solution_array[4]=$sectors->video_presentation;
$solution_array[5]=$sectors->start_free_trail;
$solution_array[6]=$sectors->hardware_package;
$solution_array[7]=$sectors->pos_market_rating;
//$solution_array[$sectors->field_id] = $sectors->value;
$id = "solution".$sectors->tab_child_id;
if ($tab_child_id != $sectors->tab_child_id) {
$id = array();
$id[$sectors->field_id] = $sectors->title;
}
else if ($tab_child_id == $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
}
//$solution_array[$id]= $id;
}
print_r($id);
//$this->load->view('compare_by_business_sectors.php');
}
This is my model code:
public function compare_business_sectors_data($sectorid) {
$query = $this->db->select('solutions.*,solution_tabs_child_fields.field_id,solution_tabs_child_fields.tab_child_id,solution_tabs_child_fields.title')
->from('solutions')
//->join('solutions', 'business_sector.sector_id = solutions.business_sector_id',"left")
->join('solution_features','solutions.entry_id = solution_features.entry_id',"left")
->join('solution_tabs_child_fields','solution_features.field_id = solution_tabs_child_fields.field_id')
->where('solutions.business_sector_id', $sectorid['id'])
->get();
return $query->result();
//print_r($query->result());exit;
}
change it as follow and try.
$id_string = "";
$id_array = array();
foreach ($business_sectors as $key=>$sectors) {
$solution_array[1]=$sectors->solution_name;
$solution_array[2]=$sectors->description;
$solution_array[3]=$sectors->vendor_name;
$solution_array[4]=$sectors->video_presentation;
$solution_array[5]=$sectors->start_free_trail;
$solution_array[6]=$sectors->hardware_package;
$solution_array[7]=$sectors->pos_market_rating;
//$solution_array[$sectors->field_id] = $sectors->value;
$id_string = "solution".$sectors->tab_child_id;
if ($tab_child_id != $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
else if ($tab_child_id == $sectors->tab_child_id) {
$id[$sectors->field_id] = $sectors->title;
}
}
print_r($id_string);
print_r($id_array);
First you are assigning string value to $id then, $id will convert to array only if first if() statement execute other wise it will not be a string. So to overcome from this keep $id_array before for loop and you can capture string in another variable.
i have a categories table
(id=1 , name=Hand made, parent=0)
(id=2 , name=Factory made, parent=0)
(id=3 , name=chairs, parent=1)
(id=4 , name=tabels, parent=1)
(id=5 , name=old chairs, parent=3)
at the menu if visitor clicked on category OLD CHAIRS , will go to page
products.php?category_id = 5
then at this page i need to know what is the main category_id , which should be HAND MADE with category_id=1
so at this page i want to say
if isset($_REQUEST['category_id']){
do the function till find the main parent,
$mainparentid = main parent category_id
}else { $mainparentid = '';
} echo $mainparentid;
here is my PHP Code
if (isset($_REQUEST['category_id'])) {
function getParent($id) {
global $connection;
$query_rsCategoryId = "SELECT * FROM categories
WHERE category_id = '".$_REQUEST['category_id']."'";
$rsCategoryId = mysql_query($query_rsCategoryId, $connection);
$row_rsCategoryId = mysql_fetch_assoc($rsCategoryId);
$parent = $row_rsCategoryId['category_parent'];
if (mysql_num_rows($rsCategoryId) < 1) {
// Error handling, entry with id $id not found
return null;
}
if ($parent == 0) {
return $id;
} else {
return getParent($parent);
}
}
$mainparentid = getParent($id);
}else {
$mainparentid ='none';
}
echo $mainparentid ;
You always input ID of the category from $_REQUEST. Change line:
WHERE category_id = '".$_REQUEST['category_id']."'";
to:
WHERE category_id = '".$id."'";
You are using parent id from request instead of given via function parameter
// notice $id instead of $_REQUEST['category_id']
$query_rsCategoryId = "SELECT * FROM categories WHERE category_id = '{$id}'";
Can someone help me as i'm new to php?
I'm running a movie site that using smarty template engine and what i'm trying to do is return and display all categories foreach movie but what happens is it displays the same category 'Comedy' for all movies when i use this
The functions
public function getByPerma($perma, $lang=null){
$perma = mysql_real_escape_string($perma);
$movie = array();
$e = mysql_query("SELECT * FROM movies WHERE perma='$perma'") or die(mysql_error());
if (mysql_num_rows($e)>0){
$movie = $this->formatMovieData(mysql_fetch_assoc($e), $lang);
}
return $movie;
}
public function getMovieCategoryDetails($movieid,$lang=null){
$movieid = mysql_real_escape_string($movieid);
$e = mysql_query("SELECT * FROM movie_tags WHERE id IN (SELECT tag_id FROM movie_tags_join WHERE movie_id=$movieid)") or die(mysql_error());
$tags = array();
if (mysql_num_rows($e)){
while($s = mysql_fetch_array($e)){
$s['tag'] = json_decode($s['tag'],true);
if ($lang){
$s['tag'] = $s['tag'][$lang];
}
$tags[$s['id']] = $s;
}
}
return $tags;
}
Called the function
$movies = $movie->getByPerma($perma,$language);
if (empty($movies)) {
$movies = '';
} else {
$tags = $movie->getMovieCategoryDetails($movies['id'],$language);
if (!count($tags)){
$smarty->assign("tags","");
} else {
$smarty->assign("tags",$tags);
}
}
And displaying the categories
{foreach from=$tags key=id item=val name=tags}
{$val.tag}
{/foreach}
I hope someone can help?
I think your getByPerma() only return 1 movie info, when add item to array, [] is missing:
$movie = $this->formatMovieData(mysql_fetch_assoc($e), $lang);
-->
$movie[] = $this->formatMovieData(mysql_fetch_assoc($e), $lang);
I have two php functions that perform rather slowly since i have a large database. One makes a request for category names. The other makes a subcategory count. Below, I have tried converting to SQL to speed up queries but not sure how to work around the foreach loop, or if this is the most efficient SQL query method. Your feedback is appreciated.
The first:
function GetCatName($catid){
global $db, $dblang, $the_cats;
foreach($the_cats as $cat){
if($cat->category_id == $catid && $cat->category_lang == $dblang)
{
$x = $cat->category_name;
}
}
return $x;
}
Rewrite to SQL:
function GetCatName($catid){
global $db, $dblang;
$sql = "SELECT category_name FROM ".table_categories." where category_id = ".$catid." and category_lang = ".$dblang.";";
$x = $db->get_result($sql);
return $x;
}
The second:
function GetSubCatCount($catid){
global $db, $the_cats;
$count = 0;
foreach($the_cats as $cat){
if(isset($cat->category_parent)){
if($cat->category_parent == $catid && $cat->category__auto_id <> 0 && $cat->category_lang == $dblang)
{
$count = $count + 1;
}
}
}
return $count;
}
Rewrite to SQL:
function GetSubCatCount($catid){
global $db, $the_cats;
$count = 0;
foreach($the_cats as $cat){
if(isset($cat->category_parent)){
$sub_cateogories = $db->get_results("SELECT * FROM ".table_categories." where category_parent = ".$cat->category__auto_id." and category_order = 0 AND category__auto_id<>0;");
$count = count($sub_cateogories);
}
}
return $count;
}
Thanks
As I mentioned in the comment you need to use $catid, otherwise the query has no improvement whatsoever.
This can be done as you did it in the first case where you replaced
$cat->category_id == $catid && $cat->category_lang == $dblang
through
category_id = ".$catid." and category_lang = ".$dblang."
This would bring us to changing the where statement to
category_parent = ".$catid." and category_order = 0 AND category_auto_id<>0
without using the foreach loop of course
I have a problem in a class I can't solve, the loop breaks in getAlojamiento() when I call getImagenes() inside the while. In this case getAlojamiento() returns only one row, it should return all the rows. Here are the methods involved:
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY, IF $id IS SET, CHECKS IF id_asoc == $id
public function getImagenes($table, $id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM $table WHERE id_asoc = '$id' ORDER BY id DESC";
}else{
$id = '';
$sql="SELECT * FROM $table ORDER BY id DESC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return = $items;
}
}
return $return;
}
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY
public function getAlojamiento($id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM tb_alojamiento WHERE id = '$id' LIMIT 1";
}else{
$id = '';
$sql="SELECT * FROM tb_alojamiento ORDER BY titulo ASC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$imagenes_arr = $this->getImagenes('tb_alo_imagenes', $f->id); //this is causing the break
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
$items[$f->id]['telefono'] = $f->telefono;
$items[$f->id]['descripcion'] = $f->descripcion;
$items[$f->id]['email'] = $f->email;
$items[$f->id]['url'] = $f->url;
$items[$f->id]['direccion'] = $f->direccion;
$items[$f->id]['ubicacion'] = $f->ubicacion;
$items[$f->id]['coordenadas'] = $f->coordenadas;
$items[$f->id]['disponibilidad'] = $f->disponibilidad;
$items[$f->id]['tarifas'] = $f->tarifas;
$items[$f->id]['servicios'] = $f->servicios;
$items[$f->id]['theme'] = $f->theme;
$items[$f->id]['premium'] = $f->premium;
$items[$f->id]['img_ppal_id'] = $f->img_ppal_id;
$items[$f->id]['imagenes'] = $imagenes_arr;
}
$return = $items;
}
}
return $return;
}
The problem is that you are using $this->dbResults for both queries. When you call getImagenes you are clobbering the dbResults in getAlojamiento.
A simple solution to avoid having the first mysql query affect other queries is to complete it first:
//first loop over the result set from first query
while($f = mysql_fetch_object($this->dbResults))
{
//note: no call to $this->getImagenes here!
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
....
}
//only now you fetch the images in a second pass
foreach( $items as $id => $item )
{
$items[$id]['imagenes'] = $this->getImagenes('tb_alo_imagenes', $id);
}
//return the complete $items array
$return = $items;
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return[] = $items;
You're setting the array to be the single $items array. You need to add it to the $return array.