PHP - How Can I Make A Proper Multi-level Thread Using Parent-child? ...
Mmm i'm not sure if i'm approaching this correctly.
Anyways, I wanted to create a multi-level thread, Where the child thread would be after the parent thread. Something like this: Hello World - Hello World - Hi! - What's up? - Hi Bob! Goodbye World - ....This guy got issues - Dude! You should watch Despicable Me! "It's so fuzzy i'm going to dieee!" Anyways, so my table looks something along the line of this: | post id | parent_id | title | body | date | 1 | NULL | Hello | Hi, i'm K | date 2 | NULL | Thread One | Body One | date 3 | 1 | Hello World | Body One | date 4 | 2 | Thread post 4 | Body One | date 5 | 1 | Thread post 5 | Body One | date 6 | 1 | Thread post 6 | Body One | date 7 | 3 | Hi What's up | Body One | date And here's the PHP code, although it's not very neat I want to clean it up and make it neater. I can only go two level deep so far. Any suggestion or recommendations? Using while & for: // Select * Threads $q = "SELECT * FROM test_db ORDER BY post_id ASC"; $r = @mysql_query($q); while ($pid_row = @mysql_fetch_object($r)) { // Array $pid_arr[] = $pid_row->post_id; // Assign Indexes to Post ID $ppid_arr[] = $pid_row->parent_id; // Assign Indexes to ParentID $md_arr = array($pid_arr, $ppid_arr); // Create multi-dimensional array matrix $parent_id = $pid_row->parent_id; } for ($i = 0; $i < count($pid_arr); $i++) { for ($a = 0; $a < count($ppid_arr); $a++) { $pid = $pid_arr[$i]; // pid = post id $ppid = $ppid_arr[$i]; // ppid = parent id //echo "<div>~~ PID $pid ~~ PPID $ppid ~~</div>"; if ($ppid === NULL) { $ppid_is_null = " & parent_id is NULL"; } else { $ppid_is_null = NULL; } // Select Top level Thread $z = "SELECT * FROM test_db WHERE post_id = '$pid'"; $y = @mysql_query($z); while ($t_row = @mysql_fetch_object($y)) { $title = $t_row->title; // title of child thread $level = $t_row->level; // level of child thread...is this useful? } // Display top level thread lvl 1 if ($ppid === NULL) { // If the parent_id is NULL, display top level thread echo '<div>PID: ' . $pid . ' || PPID: ' . $ppid . " || Title: " . $title . "</div><br>\n"; $post = $pid; // PostID = 1 $parent = $ppid; // Parent ID ex: [1] // Get child id, where parent id = [1] // trying to get the child thread here...but it's not working $child_q = "SELECT * FROM test_db WHERE parent_id = '$post'"; $child_r = @mysql_query($child_q); while($c_row = @mysql_fetch_object($child_r)) { $c_arr[] = $c_row->post_id; $c_ppid_arr[] = $c_row->parent_id; } for ($n = 0; $n < count($c_arr); $n++) { if ($c_ppid_arr[$n] === $post) { echo "<div>$c_arr[$n]</div>"; } } break; //echo "<div>PID: $pid</div>"; } break; } } Using While: <?php require_once('db_connection'); echo '<hr><hr><br>'; // I just realized that selecting * where parent id is null might limit the amount of rows retrieved. // Query to select threads $n = NULL; $q = "SELECT * FROM test_db WHERE (test_db.parent_id is NULL) Order By date ASC"; $r = @mysql_query($q); while ($threads = @mysql_fetch_object($r)){ $pid = $threads->post_id; $sid = $threads->subject_id; $parent_id = $threads->parent_id; $title = $threads->title; $body = $threads->body; echo '<div>PostID: ' . $pid . ' || Parent: ' . $parent_id . ' || SubjectID: ' . $sid . ' || Title: ' . $title . ' || Body: ' . $body . '</div>'; $q2 = "SELECT * FROM test_db WHERE parent_id = '$pid' Order by date DESC"; $r2 = @mysql_query($q2); while ($level2 = @mysql_fetch_object($r2)) { $level2_pid = $level2->post_id; $level = 1.5 *($level2->level); // lvl 2: 3em echo '<div style="text-indent:' . $level . 'em">' . 'PostID: ' . $level2->post_id . ' || ParentID: ' . $level2->parent_id . '</div>'; $q3 = "SELECT * FROM test_db WHERE parent_id = '$level2_pid'"; $r3 = @mysql_query($r3); while ($level3 = @mysql_fetch_object($r3)) { $level3 = 1.5 + $level; echo '<div style="text-indent:' . $level3 . 'em">' . 'PostID: ' . $level3->post_id . ' || ParentID: ' . $level3->parent_id . '</div>'; } } } ?> I'm not a comp. sci major or anything, so I'm learning this as I go. Any help would be greatly appreciated. It seems like the while & for is more practical, but i'm not quiet sure. What am I doing wrong? - K I just joined this forum today ^_^ Hope to be good friends with you guys and gals Similar TutorialsI have one table but i try to make like the result not finished.
Hmm.. can you see my table :
FireShot Screen Capture #003 - 'localhost _ 127_0_0_1 _ pmis_dbase _ rekening_kegiatan I phpMyAdmin 4_0_4_1' - localhost_phpmyadmin_index_php_db=pmis_dbase&table=rekening_kegiatan&target=sql_php&token=93960ef7b5.png 803.36KB
0 downloads
I want to declare sum for parent kd_rekening in same row for "Anggaran" => jns_anggaran =1 and "Perubahan" => jns_anggaran = 2. And child ust load field nilai. Untitled.jpg 34.7KB 0 downloads Thanks before Hi I am trying to create a hierarchy array from our mysql database. What i have so far is: //instantiate DB & connect $database = new Database(); $db = $database->connect(); //instantiate question object $question = new Question($db); //query $results = $question->read(); //check for data if ($results) { $question_arr['questions'] = array(); $child_arr = array(); while ($row = $results->fetch(PDO::FETCH_ASSOC)) { array_push($question_arr['questions'], $row); $question_arr['questions'][] = buildTree($row); } print_r($question_arr['questions']); } else { echo json_encode(array('message'=>'nothing here!.')); } function buildTree($child) { $branch = array(); foreach ($child as $row) { $childresults = $question->read_children($row['parentid']); while ($childrow =$childresults->fetch(PDO::FETCH_ASSOC)) { $children = buildTree($childrow); if ($children) { $row['children'] = $children; } $branch[] = $childrow; } } //} return $branch; } in my Questions.php file: <?php class Question{ private $conn; public $id; public $childid; public $parentid; public $question; public $pageid; public $numclicks; public $typeid; public $date_created; // Constructor with DB public function __construct($db) { $this->conn = $db; } public function read() { //create query(sql statement) $query = 'SELECT id as parentid, question, pageid, typeid,numclicks,date_created from ct_questions'; // Prepare statement $stmt =$this->conn->prepare($query); // Execute query $stmt->execute(); return $stmt; } public function read_children($parentid) { //This is from a View I created in Mysql $query = 'SELECT parent_question, parentid, parent_pageid, child_question, childid, child_pageid from ct_vquestion_parent_child_lookup where parentid='.$parentid.''; // Prepare statement $stmt = $this->conn->prepare($query); // Execute query $stmt->execute(); return $stmt; } }
the current errors i am getting a <br /> <b>Notice</b>: Undefined variable: question in <b>C:\htdocs\api\questions\read.php</b> on line <b>41</b><br /> <br /> <b>Fatal error</b>: Uncaught Error: Call to a member function read_children() on null in C:\htdocs\api\questions\read.php:41 Stack trace: #0 C:\htdocs\api\questions\read.php(28): buildTree(Array) #1 {main} thrown in <b>C:\htdocs\api\questions\read.php</b> on line <b>41</b><br /> In javascript you can do multiple methods on the same line like: if(document.getElementById('myElement').className.match(/^[0-9]/)){/*Do something*/} in that we have getElementById() and match() on the same line, and it works the same as if you were to split them on multiple lines. Is it possible to do that with php? For example: $obj = new MyObject(); $obj->add(2, 3)->to_string(); Hi all I have a menu function which basically produces a menu which looks like Code: [Select] Products Apple iMac iPod iPhone Microsoft Windows Office and the code I use is; THE FUNCTION function menu($parentID, $mymenu) { $html = ""; if (isset($mymenu['parentID'][$parentID])) { $html .= " <ul>\n"; foreach ($mymenu['parentID'][$parentID] as $menu_id) { if(!isset($mymenu['parentID'][$menu_id])) { $html .= "<li>\n <a href='/".$mymenu['menu_item'][$menu_id]['url']."'>".$mymenu['menu_item'][$menu_id]['value']."</a>\n</li>"; } if(isset($mymenu['parentID'][$menu_id])) { $html .= "<li>\n <a href='/".$mymenu['menu_item'][$menu_id]['url']."'>".$mymenu['menu_item'][$menu_id]['value']."</a>"; $html .= menu($menu_id, $mymenu); $html .= "</li>"; } } $html .= "</ul>"; } return $html; } CREATE MENU CODE $result = mysql_query("SELECT id, value, url, parentID FROM menu WHERE active = 1 AND deleted = 1 ORDER BY position ASC"); $mymenu = array('menu_item' => array(),'parentID' => array()); while ($menu_item = mysql_fetch_assoc($result)) { $mymenu['menu_item'][$menu_item['id']] = $menu_item; $mymenu['parentID'][$menu_item['parentID']][] = $menu_item['id']; } echo menu(0, $mymenu); The problem I have is the URLS, at the moment the menu URLS are outputted as Code: [Select] Products - http://localhost/Products Apple - http://localhost/Apple iMac - http://localhost/iMac iPod - http://localhost/iPod But I need to alter my function so that URLS are outputted as Code: [Select] Products - http://localhost/Products Apple - http://localhost/Products/Apple iMac - http://localhost/Products/Apple/iMac iPod - http://localhost/Products/Apple/iPod Is this at all possible? Thanks very much everyone John What am I missing here? The array: protected $form_bonus = array( "Attacker" => array( "Ashwin" => array( "normal" => 1.15, "rps" => 1.38), "Cordelon" => array( "normal" => 1.15, "rps" => 1.38), "Mersan" => array( "normal" => 1.15, "rps" => 1.38), "Phlanixian" => array( "normal" => 1.195, "rps" => 1.494), "Slythe" => array( "normal" => 1.15, "rps" => 1.38) ), "Defender" => array( "Ashwin" => array( "normal" => 1.15, "rps" => 1.38), "Cordelon" => array( "normal" => 1.15, "rps" => 1.38), "Mersan" => array( "normal" => 1.15, "rps" => 1.38), "Phlanixian" => array( "normal" => 1.15, "rps" => 1.38), "Slythe" => array( "normal" => 1.15, "rps" => 1.38) ) ); accessing it: $bonus *= form_bonus[$this->role][$this->race]['rps']; error: PHP Parse error: syntax error, unexpected '[' db table username------>id->username->cash->points->referrer
db table referral_levels------>id->level->earnings->signupBonusCash->signupBonusPoints->status
username referrer -------- -------- admin kelly88 admin // UPDATE USERNAME ADMIN WITH referral level 1 POINTS/CASH // jacob kelly88 // UPDATE USERNAME ADMIN WITH referral level 2 POINTS/CASH AND USERNAME kelly88 WITH referral level 1 POINTS/CASH // david16 jacob // UPDATE USERNAME ADMIN WITH referral level 3 POINTS/CASH AND USERNAME kelly88 WITH referral level 2 POINTS/CASH AND USERNAME jacob WITH referral level 1 POINTS/CASH //Is this possible. If yes - HOW? Current test registration code with referral level 1 <?php if(!empty($_GET['ref'])){ $referrerUsername = filter_input(INPUT_GET, 'ref', FILTER_SANITIZE_STRING); if(usernameExist($referrerUsername, $db) === TRUE){ $_SESSION['ref'] = $referrerUsername; } } // define variables with the value for each field // the value from POST,GET if this exist, or an empty value $errors = array(); $username = isset($_POST['username']) ? filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING) : ''; $referrer = !empty($_SESSION['ref']) ? $_SESSION['ref'] : (isset($_POST['referrer']) ? filter_input(INPUT_POST, 'referrer', FILTER_SANITIZE_STRING) : ''); if(!empty($_POST['submit'])){ if(empty($username)){ $errors[] = $lang['error']['a_019']; } else if(validUsernameLenght($username) === FALSE){ $errors[] = $lang['error']['a_020']; } else if(validUsernameChars($username) === FALSE){ $errors[] = $lang['error']['a_021']; } else if(usernameExist($username, $db) === TRUE){ $errors[] = $lang['error']['a_022']; } if(!empty($referrer)){ if(usernameExist($referrer, $db) === FALSE){ $errors[] = $lang['error']['a_037']; } else if($username == $referrer){ $errors[] = $lang['error']['a_038']; } } } if(!empty($_POST['submit']) and empty($errors)){ /* $queryOne = 'INSERT INTO users(username, referrer) VALUES (:username, :referrer)'; $insertOne = $db->prepare($queryOne); $insertOne->bindParam(':username', $username, PDO::PARAM_STR); $insertOne->bindParam(':referrer', $referrer, PDO::PARAM_STR); $successOne = $insertOne->execute(); */ if($referrer){ $query = 'SELECT signupBonusCash AS sbc, signupBonusPoints AS sbp FROM referral_levels WHERE level = 1 AND status = "enabled"'; $select = $db->query($query); $row = $select->fetch(PDO::FETCH_ASSOC); $queryTwo = 'UPDATE users SET points = points + :points, cash = cash + :cash WHERE username = :referrer'; $selectTwo = $db->prepare($queryTwo); $selectTwo->bindParam(':cash', $row['sbc'], PDO::PARAM_STR); $selectTwo->bindParam(':points', $row['sbp'], PDO::PARAM_STR); $selectTwo->bindParam(':referrer', $referrer, PDO::PARAM_STR); $selectTwo->execute(); } } if(!empty($errors)){ foreach($errors as $error){ print $error.'<br>'; } } print ' <form method="POST"> <table style="width:100%"> <tr> <td style="width:30%;font-weight:bold">Username</td> <td style="width:70%"><input type="text" name="username" maxlength="255" style="width:200px" value="'.cleanOutput($username).'"></td> </tr>'; if(!empty($_SESSION['ref'])){ print ' <tr> <td style="font-weight:bold">'.$lang['global']['a_047'].'</td> <td><input type="text" name="referrer" readonly="readonly" maxlength="255" style="width:200px" value="'.cleanOutput($referrer).'"></td> </tr>'; }else{ print ' <tr> <td style="font-weight:bold">'.$lang['global']['a_047'].'</td> <td><input type="text" name="referrer" maxlength="255" style="width:200px" value="'.cleanOutput($referrer).'"></td> </tr>'; } print ' <tr> <td colspan="2" style="text-align:center"><input type="submit" name="submit" value="Submit"></td> </tr> </table> </form>'; ?> I want to have a multi level dropdown selection tool come out of an array (not database; almost all of available codes on the internet are based on mysql databse). I have an array as each element has this format: "Country | City | ID". Using explode, I want to make a dropdown to choose the country, then choosing the cities of the chosen country. Finally, in a simple search box make action="result.php" to lead to result.php?q=$id Thanks for your kind attention $form_bonus = array( "Attacker" => array( "Ashwin" => array( "normal" => 1.15, "rps" => 1.38), "Cordelon" => array( "normal" => 1.15, "rps" => 1.38), "Mersan" => array( "normal" => 1.15, "rps" => 1.38), "Phlanixian" => array( "normal" => 1.195, "rps" => 1.494), "Slythe" => array( "normal" => 1.15, "rps" => 1.38) ), "Defender" => array( "Ashwin" => array( "normal" => 1.15, "rps" => 1.38), "Cordelon" => array( "normal" => 1.15, "rps" => 1.38), "Mersan" => array( "normal" => 1.15, "rps" => 1.38), "Phlanixian" => array( "normal" => 1.15, "rps" => 1.38), "Slythe" => array( "normal" => 1.15, "rps" => 1.38) ) ); echo "<pre>".print_r($form_bonus)."</pre>"; output: 1 what am i missing here? I want to create an array from a file with this structure TITLE1, HEADER1, key11, key12, key13, key14 TITLE2, HEADER2, key21, key22, key23, key24 . . . How I can get a foreach with these elements: $title="TITLE" $header="HEADER" $key="(one random key)" If needed, I can change the file structure too. Hi guys, I'm still not having any luck with coming up with an idea of how to make my multi-level drop down menu work with items from a database. I don't necessarily need code, but an idea of how to make it work, so any ideas are welcome. The table: Column Descriptions: id - The unique id label - The text to display link - The link to be used relation - I cannot remember why I wanted that... just disregard it parent - The parent item's id (0 for no parent) sort - A sort number for the item (ascending) active - 0 for false, 1 for true (not implemented yet, will add a WHERE `active` = 1 into the sql later) depth - How many parent items there are Now, here's what it has to do (the class): Grab items from the database (sorted by depth, parent, and sort) Place the children in a child array of the parents (or however it can be sorted) Implode the array and turn it into an html menu with the below structure Menu HTML Structure Code: [Select] <div id="menu"> <ul> <li><h2>Level 1 A</h2> <ul> <li><a href="?r=level2/a">Level 2 A</a> <ul> <li><a href="?r=level3/a">Level 3 A</a></li> <li><a href="?r=level3/b">Level 3 B</a></li> </ul> </li> </ul> </li> <li><a href="?r=level1/b"><h2>Level 1 B</h2></a></li> </ul> </div> And here is the code I have so far, but I can't figure out how to get the children into the parent array, or at least sort it so that I can achieve the above HTML structure. Thank you in advance for your help, and as I said above, I don't necessarily need code, but an idea of how to make it work, so any ideas are welcome. Hello. i have some code that works with out using parent and child but i dont think im doing it in the correct oop way. would someone maybe please just have a little look for me please. by the way.. i know im not ment to use global but thats how i was shown to do that on my tutorial videos.. i'll address that in another post so. in this example i have this pages class Code: [Select] <?PHP require_once(LIB_PATH.DS.'database.php'); class Pages { protected static $table_name="pages"; protected static $db_fields = array( 'id', 'pageName', 'contTemp_id', 'contElements_id', 'title', 'sub_title', 'description', 'about', 'image', 'created', 'dateMod', 'timeMod'); public $id; public $pageName; public $contTemp_id; public $contElements_id; public $title; public $sub_title; public $description; public $about; public $image; public $created; public $dateMod; public $timeMod; // "new" is a reserved word so we use "make"(or "build") public static function make( $id="", $pageName="", $contTemp_id="", $contElements_id="", $title="", $sub_title="", $description="", $about="", $image="", $created="", $dateMod="", $timeMod="") { if(!empty($title)) { $kw = new NavL3(); $kw->id = (int)$id; $kw->pageName = $pageName; $kw->contTemp_id = (int)$contTemp_id; $kw->contElements_id = (int)$contElements_id; $kw->title = $title; $kw->sub_title = $sub_title; $kw->description = $description; $kw->about = $about; $kw->image = $image; $kw->created = $created; $kw->dateMod = $dateMod; $kw->timeMod = $timeMod; return $kw; }else{ return false; } } //end function make public static function find_by_pageName($id){ global $database; $sql = "SELECT * FROM ".self::$table_name." WHERE id='".$database->escape_value($id)."'"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } public static function find_by_pageID($pageID=0){ global $database; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$database->escape_value($pageID)." LIMIT 1"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } // Common Database Methods public static function find_all(){ global $database; $sql = "SELECT * FROM ".self::$table_name.""; return self::find_by_sql($sql); } public static function find_by_id($id=0){ global $database; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$database->escape_value($id)." LIMIT 1"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } public static function find_by_sql($sql){ global $database; $results_set = $database->query($sql); $object_array = array(); while($row = $database->fetch_array($results_set)){ $object_array[] = self::instantiate($row); } return $object_array; } public static function count_all(){ global $database; $sql = "SELECT COUNT(*) FROM ".self::$table_name; $results_set = $database->query($sql); $row = $database->fetch_array($results_set); return array_shift($row); } public static function instantiate($result){ $object = new self; foreach($result as $attribute => $value){ if($object->has_attribute($attribute)){ $object->$attribute = $value; } } return $object; } private function has_attribute($attribute){ $object_vars = $this->attributes(); return array_key_exists($attribute, $object_vars); } protected function attributes(){ $attributes = array(); foreach(self::$db_fields as $field){ if(property_exists($this, $field)){ $attributes[$field] = $this->$field; } } return $attributes; } protected function sanitized_attributes(){ global $database; $clean_attributes = array(); foreach($this->attributes() as $key => $value){ $clean_attributes[$key] = $database->escape_value($value); } return $clean_attributes; } public function save(){ return !empty($this->id) ? $this->update() : $this->create(); } public function create(){ global $database; $attributes = $this->sanitized_attributes(); $sql = "INSERT INTO ".self::$table_name." ("; $sql .= join(", ", array_keys($attributes)); $sql .= ") VALUES ('"; $sql .= join("', '", array_values($attributes)); $sql .= "')"; if($database->query($sql)){ $this->id = $database->insert_id(); return true; }else{ return false; } } public function update(){ global $database; $attributes = $this->sanitized_attributes(); $attribute_pairs = array(); foreach($attributes as $key => $value){ $attribute_pairs[] = "{$key}='{$value}'"; } $sql = "UPDATE ".self::$table_name." SET "; $sql .= join(", ", $attribute_pairs); $sql .= " WHERE id=".$database->escape_value($this->id); $database->query($sql); return ($database->affected_rows() == 1) ? true : false; } public function delete(){ global $database; $sql = "DELETE FROM ".self::$table_name." "; $sql .= "WHERE id=".$database->escape_value($this->id); $sql .= " LIMIT 1"; $database->query($sql); return ($database->affected_rows() == 1) ? true : false; } } //end class blogs ?> and i have this conttemp class Code: [Select] <?PHP require_once(LIB_PATH.DS.'database.php'); class Conttemps { protected static $table_name="contTemps"; protected static $db_fields = array( 'id', 'name', 'created', 'dateMod', 'timeMod'); public $id; public $name; public $created; public $dateMod; public $timeMod; // "new" is a reserved word so we use "make"(or "build") public static function make( $id, $name="", $created="", $dateMod="", $timeMod="") { if(!empty($name)) { $kw = new Templates(); $kw->id = (int)$id; $kw->name = $name; $kw->created = $created; $kw->dateMod = $dateMod; $kw->timeMod = $timeMod; return $kw; }else{ return false; } } //end function make public function find_contTemp($pageID){ $page = Pages::find_by_pageID($pageID); $pageCID = $page->contTemp_id; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$pageCID.""; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } // Common Database Methods public static function find_all(){ global $database; $sql = "SELECT * FROM ".self::$table_name.""; return self::find_by_sql($sql); } public static function find_by_id($id=0){ global $database; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$database->escape_value($id)." LIMIT 1"; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } public static function find_by_sql($sql){ global $database; $results_set = $database->query($sql); $object_array = array(); while($row = $database->fetch_array($results_set)){ $object_array[] = self::instantiate($row); } return $object_array; } public static function count_all(){ global $database; $sql = "SELECT COUNT(*) FROM ".self::$table_name; $results_set = $database->query($sql); $row = $database->fetch_array($results_set); return array_shift($row); } public static function instantiate($result){ $object = new self; foreach($result as $attribute => $value){ if($object->has_attribute($attribute)){ $object->$attribute = $value; } } return $object; } private function has_attribute($attribute){ $object_vars = $this->attributes(); return array_key_exists($attribute, $object_vars); } protected function attributes(){ $attributes = array(); foreach(self::$db_fields as $field){ if(property_exists($this, $field)){ $attributes[$field] = $this->$field; } } return $attributes; } protected function sanitized_attributes(){ global $database; $clean_attributes = array(); foreach($this->attributes() as $key => $value){ $clean_attributes[$key] = $database->escape_value($value); } return $clean_attributes; } public function save(){ return !empty($this->id) ? $this->update() : $this->create(); } public function create(){ global $database; $attributes = $this->sanitized_attributes(); $sql = "INSERT INTO ".self::$table_name." ("; $sql .= join(", ", array_keys($attributes)); $sql .= ") VALUES ('"; $sql .= join("', '", array_values($attributes)); $sql .= "')"; if($database->query($sql)){ $this->id = $database->insert_id(); return true; }else{ return false; } } public function update(){ global $database; $attributes = $this->sanitized_attributes(); $attribute_pairs = array(); foreach($attributes as $key => $value){ $attribute_pairs[] = "{$key}='{$value}'"; } $sql = "UPDATE ".self::$table_name." SET "; $sql .= join(", ", $attribute_pairs); $sql .= " WHERE id=".$database->escape_value($this->id); $database->query($sql); return ($database->affected_rows() == 1) ? true : false; } public function delete(){ global $database; $sql = "DELETE FROM ".self::$table_name." "; $sql .= "WHERE id=".$database->escape_value($this->id); $sql .= " LIMIT 1"; $database->query($sql); return ($database->affected_rows() == 1) ? true : false; } } //end class blogs ?> the bit im interested in is this function in the Conttemp class Code: [Select] public function find_contTemp($pageID){ $page = Pages::find_by_pageID($pageID); $pageCID = $page->contTemp_id; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$pageCID.""; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } it call a function in from the Pages class. i could take the function from here and put it in the Pages class i guess but i was wondering about Exends. should i do class Conttemps extends Pages { and use something like Code: [Select] public function find_contTemp($pageID){ $pageCID= Pages::contTemp_id; $sql = "SELECT * FROM ".self::$table_name." WHERE id=".$pageCID.""; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } i guess that wont work because its not getting the $pageID but anyway.. any thoughts ???? thanks rick Ok, here is the whole code for the downline, but the problem is that it doesn't show members below that one I mean if b follows a, and c follows b and I opened the page of A, it will only show A's info, and not bring B and C in the downline Code: [Select] <?php if($_REQUEST["i"]){ GenerateTree($_REQUEST["i"]); } else{ GenerateTree($_GET['id']); } function GenerateTree($memberid){ $l1="<img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' />";$l2="<img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' />"; $query = "SELECT * FROM users where recruiteris='".$memberid."' order by type"; //echo $query; $result = mysql_query($query); //var_dump($result); while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { if($row["type"]=="Company"){$l1=getDownline($row["id"]);} if($row["type"]=="client"){$l2=getDownline($row["id"]);} } mysql_free_result($result); echo "<table border='0' class='mainTable' cellspacing='0' cellpadding='3' style='width:100%'>\n"; echo "<tr><td colspan='3' style='text-align:center;'>Login ID: ".$memberid.getInfo($memberid)."<br />"."</td></tr>"; echo "<tr><td colspan='3'>".getDownline($memberid)."</td></tr>"; echo "<tr><td style='width:33%;'>".$l1."</td><td style='width:33%;'>".$l2."</td>"; echo "</table>\n"; } function getDownline($memberid){ $query = "SELECT * FROM users where recruiteris='".$memberid."' order by type"; //echo $query; $result = mysql_query($query); //var_dump($result); $final = "<table border='0' style='width:100%;' class='internalTable' cellspacing='0' cellpadding='2'>\n"; $final .= "<tr>"; $nothing=true; $x=0; $pre; while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { $x++; $_SESSION['s']=0; if($row["type"]=="Company" && $x==1){$final .= "<td style='width:33%; background-color:#FFFFEC;' title='".getToolTip($row["login_id"])."'><a href='gen.php?i=".$row["login_id"]."'>".$row["login_id"]."</a><br />".$row["m_name"]."<br />Position: ".$row["form_type"]."<br />Downline - ".getCount($row["login_id"]).$_SESSION['s']."</td>";} if($row["type"]=="client" && $x==2){$final .= "<td style='width:33%; background-color:#E1F0FF;' title='".getToolTip($row["login_id"])."'><a href='gen.php?i=".$row["login_id"]."'>".$row["login_id"]."</a><br />".$row["m_name"]."<br />Position: ".$row["form_type"]."<br />Downline - ".getCount($row["login_id"]).$_SESSION['s']."</td>";} if($row["type"]=="client" && $x==1){$final .= "<td style='width:33%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td><td style='width:33%; background-color:#E1F0FF' title='".getToolTip($row["login_id"])."'><a href='gen.php?i=".$row["login_id"]."'>".$row["login_id"]."</a><br />".$row["m_name"]."<br />Position: ".$row["form_type"]."<br />Downline - ".getCount($row["login_id"]).$_SESSION['s']."</td>";} $pre = $row["type"]; $nothing=false; } if($nothing){$final .= "<td style='width:33%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td><td style='width:34%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td>"; } if($x==1 && $pre=="Company"){$final .= "<td style='width:33%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td>";} mysql_free_result($result); $final .= "</tr>"; $final .= "</table>\n"; return $final; } function getToolTip($id){ $query = "SELECT * FROM users where id ='".$id."'"; $result = mysql_query($query); $res; while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { $res = "fade=[off] cssheader=[toolHeader] cssbody=[toolBody] header=[Detail For ID () - ".$id."] body=[".$row["m_name"]."<br />Address:<br />".$row["address"]."]"; } mysql_free_result($result); return $res; } function getInfo($id){ $query = "SELECT * FROM users where id='".$id."'"; $result = mysql_query($query); $res; while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { $res = "<br />Name: ".$row["fname"]."<br />National ID: ".$row["nid"]."<br />"; } mysql_free_result($result); return $res; } function getCount($id){ $query = "SELECT * FROM users where recruiteris='".$id."'"; $result = mysql_query($query); $count = mysql_num_rows($result); $_SESSION['s'] = $_SESSION['s']+$count; while ($row = mysql_fetch_array($result, MYSQL_BOTH)) { getCount($row["id"]); } mysql_free_result($result); //echo $count."<br />"; return ""; } // Closing connection mysql_close($link); ?> Hi, I've a two classes A,B. A is a parent class and B is a child class. B is extends from A. I made an object of class A. Now i want to access function of class B from this object instance. e.g Code: [Select] class A { function myfunctiona() { ....... ....... } } class B extends A { function chlidfunction() { return "hyne"; } } $sani = new A(); //here i want to access echo $sani->b->childfunction(); please guide how can called child class function from parent object instance? Thanks Code: [Select] Main Object ( [Visitor] = Visitor Object ( [user_info] => Array ( [username] = user [user_id] = 1 ) ) [Room] = Room Object ( [info] = Array( [id] = 1 [name] = Lobby ) [messages] = Messages Object ( [messages] = Array ( [0] = Array() ) ) ) ) Is there a way to get the visitor info within the Messages Object? I'm building it such as $Main = new Main; $Main->Visitor = new Visitor; $Main->Room = new Room; $Main->Room->Messages = new Messages; so they're not static I know that I can pass the $this var through each but that duplicates the class each time and I'm 99% sure that's bad. Why won't my unset remove the array from the parent $data[0] array? Code: [Select] foreach ($data[0] as $k => $r) { if (($r['feedid'] !== $user_info['uid']) && ($r['action_id'] == 'newuser')) { unset($data[0][$k]); } } I have a major problem; I have two tables - Category and Product The catID is the primary key for Category and acts as the foreign key for Product. I have some example data below; CATEGORY catID: 3 cat: Pink PRODUCT prodID: 1 product: Fuchsia catID: 3 prodID: 2 product: Dark Pink catID: 3 what I want is the page to display the data like this? Header: Pink Content: Fuchsia Dark Pink Below is the code thus far; Code: [Select] <?php error_reporting(E_ALL ^ E_NOTICE); ini_set("display_errors", 1); require ('includes/config.inc.php'); include ('./includes/header.html'); require (MYSQL); include ('./includes/main.html'); if($id = isset($_GET['catID'])) { $q = ('SELECT `category`.`catID` , `category`.`cat` , `product`.`product` FROM `product` LEFT JOIN `hairext`.`category` ON `product`.`catID` = `category`.`catID` WHERE `product`.`catID`="'.$_GET['catID'].'"'); $r = mysqli_query($dbc, $q); echo '<div id="right">'; $num = mysqli_num_rows($r); for ($j = 0 ; $j < $num ; ++$j) { $row = mysqli_fetch_row($r); echo '<h1>' . $row[1] . '</h1>'; } while($row = mysqli_fetch_array($r)) { echo '<p>'; echo $row[2]; echo "<br />"; echo '</p>'; } echo '</div>'; } include ('./includes/footer.html'); ?> At the moment, this is not doing what I want, I apologise if this is very long winded, but how do I solve this problem please? I have a user class that is very dependent on the database class, which is why the user class extends the database. I tried creating a protected method in the parent class called getDBCObject, which returned the database object/variable/handle that I want the user to have access to. I tried the method below, but it doesn't work: <?php /* * @DATABASE * ~~~~~~~~~~~~ * @FILE DESCRIPTION: Handles all database related processes * @LAST MODIFIED: April 4, 2012 */ class database { protected $dbc; function __construct($db_host, $db_name, $db_user, $db_password) { try { $this->dbc = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_password); } catch(PDOException $e) { echo '<b>An error occured while trying to create a database connection: </b>'. $e->getMessage(); } } /* * @METHOD getDBCObject * @DESC Gives the $dbc object/variable to its child classes */ protected function getDBCObject() { return $this->dbc; } } ?> My user class: <?php /* * @DATABASE * ~~~~~~~~~~~~ * @FILE DESCRIPTION: User related proccess * @LAST MODIFIED: April 5, 2012 */ class user extends database { protected $dbc; public function __construct() { if(parent::getDBCObject() == null) { echo '<br/>A database class/connection is required before creating the user class.'; } } public function isLoggedIn() { if($_COOKIE['user']) { //soon to come } else { return false; } } } ?> Any feedback on how I can let the user class use the $dbc variable in the database class? class Database { // actual database interaction // also uses mysql_real_escape etc. } class Users extends Database { function checkIfUsernameExists() { } } class addUser extends Users { // perform all add user stuff } class searchUser extends Users { // all search user stuff } So, to add a new user, I would instantiate, then perform various queries to the addUser class, probably also using the checkIfUsernameExists method in the Users class. Finally, Database would add the record. Question: what do I instantiate? Do I instantiate just the addUser one, or first the Database class? I know how to do it, but what about instantiation, using parent:: self:: etc. etc. (how do I link these clasess together is what I think I mean). I'm pulling a list of topics from my DB and they are structured hierarchally using the typical id | parent_id scheme The array I end up with from the DB is one large one with keys representing the unique id of each data result...The problem is getting past the 2d scope of the array. I know this will require a recursive function and I've been at it for hours but can't seem to wrap my hurting head around it! How do I get my orignal array in this form: Array ( [0] => Array ( [1] => top parent [2] => top parent [3] => top parent [9] => top parent ) [2] => Array ( [4] => #1 child of 2 [5] => #2 child of 2 ) [3] => Array ( [6] => #1 child of 3 ) [4] => Array ( [7] => #1 child(subsub) of 4 [8] => #2 child(subsub) of 4 ) ) To look something more like this? : Array ( [1] => top parent [2] => Array ( [4] => Array ( [7] => #1 child(subsub) of 4 [8] => #2 child(subsub) of 4 ) [5] => #2 child of 2 ) [3] => Array ( [6] => #1 child of 3 ) [9] => top parent ) notice how the 2nd array has all the proper dimensions according the the DB hierarchy. Thank you ps. or maybe I should work from a different array to start from...I'm open to suggestions I have these two classes: Code: [Select] <?php class A { private $id; public function __construct() { $this->id = '11111'; } public function getProperty($prop) { return $this->$prop; } }?> Code: [Select] <?php class B extends A { private $message = "Nope, can't see it"; public function __construct() { parent::__construct(); $this->message = "Yep, I can see it"; } }?> I tried this, but it just outputs the id (the first call) Code: [Select] $class = new B; echo $class->getProperty('id'); echo $class->getProperty('message'); Why is that? I thought I could use a parent method on a child property.. *EDIT* Using a public or protected visibility on the message property gets me the output I expect...how come? |