PHP - Creating Tree-like Structure (item, Sub Item, Subsubitem) From A Db?
Hi there,
I think this is a big question but I'd appretiate any help you can provide!! I have a list of items and subitems in a table that looks like this: id parent_id title 1 0 House Chores 2 1 Take Out Trash 3 1 Clean Room 4 0 Grocery List 5 4 Eggs 6 4 Produce 7 6 Lettuce 8 6 Tomato 9 4 Milk I want to display it like this: (+) House Chores: > Take Out Trash > Clean Room (+) Grocery List: > Eggs (+) Produce > Letutce > Tomato > Milk So basically each entry in the table has an unique id and also a parent id if it's nested inside another item. I "sort of" got it figured out in one way, but it doesnt really allow for nested subgroups. I'd like to know how would y'all PHP freaks to this Also taking suggestions for the javascript code to expand/collapse the tree !! Thank you! Similar TutorialsI have a script that seems to work well to insert a bookmark into a users database when he/she is logged into the system but I am having a hard time figuring out how I would go about making a work-a-round for having an item selected before being logged in, and inserted after they have logged in or registered. For example, I would like a user to be able to select an Item to add to bookmark whether that user is logged in/registered or not and if they are not, they would be greeted with a login/registration form and after successful login the add bookmark script would be initiated on the item previously selected. What I've got this far: Simple form to add bookmark: <form name="bm_table" action="add_bms.php" method="post"> <input type="text" name="new_url" value="http://" /> <input type="submit" value="Add Bookmark"/> </form> Then I have the add bookmark script: BEGIN php $new_url = $_POST['new_url']; try { check_valid_user(); //cannot get past this part since it ends the script....code below if (!filled_out($_POST)) { throw new Exception('Form not completely filled out.'); } // check URL format if (strstr($new_url, 'http://') === false) { $new_url = 'http://'.$new_url; } // check URL is valid if (!(@fopen($new_url, 'r'))) { throw new Exception('Not a valid URL.'); } // try to add bm add_bm($new_url); echo 'Bookmark added.'; // get the bookmarks this user has saved if ($url_array = get_user_urls($_SESSION['valid_user'])) { display_user_urls($url_array); } } catch (Exception $e) { echo $e->getMessage(); } END php Checking valid user - the portion I cannot get past in the above script: function check_valid_user() { // see if somebody is logged in and notify them if not if (isset($_SESSION['valid_user'])) { echo "Logged in as ".$_SESSION['valid_user'].".<br />"; } else { // they are not logged in do_html_heading('Problem:'); echo 'You are not logged in.<br />'; do_html_url('login.php', 'Login'); do_html_footer(); exit; } } How would I go about modifying the script so that a user could fill in the form (later it would be a link...obviously they probably wouldn't be filling in a form that is log-in specific - but same concept I think) Thanks in advance for the help! tec4 Hello: I would like to create a little CMS that will allow me to create a new Category (a State - one text field), then a Subcategory (A Town - one text field) that can be assigned to a State, and then a Menu Item (With a few text fields, a textarea, and a photo upload) that can be assigned to a Town. I have made these before with old ASP code but want to start develpoing this in PHP. I believe I found a demo of a Product Catalog online and worked from there. Can someone put me in the right direction? Or show me where I can fine a sample of this. I want to make it so it can be modified or deleted, if needed, but not to delete something if it's assigned to something (like not being able to delete a SubCategory if there are 3 Menu Items assigned to it). I would appreciate any help or direction. Thanks! Well I am looking to change this url Code: [Select] http://website.com/product.php?Item=2369 to Code: [Select] http://website.com/product.php?Item=Item-Name Heres a snip of the code that handles that. <?php include_once('mysql_connect.php');$id = (int)$_GET['Item'];?>() any help would be appreciated. Hey guys, I have a bunch of categories and products in a tree format. For several reasons I need to restructure them from the tree format into a flattened format. I have 2 arrays, one full of categories, the other products. Each category and product has an ID, and a reference to it's parent's ID. The top level categories reference to 0. What I need is to have the categories output like thus: Top Level Categories: Category 1 Category 2 Category 1 Sub category 1 Sub category 2 Category 2 Sub category 3 Sub category 4 Sub category 1 Product 1 Product 2 Sub category 2 Product 3 Product 4 Sub category 3 Product 5 Product 6 Sub category 4 Product 7 Product 8 There could be an unlimited number of sub categories within categories before we get to products, so this needs to be done through a function, however I cannot for the life of me think how to do this. Initially I thought about using 2 arrays, a buffer of categories outputted, and a queue of categories to be outputted, but quickly realised that when I go more than 2 layers deep I can't keep track of the queue's properly. Hi, I am working on a project, where i want to add sub-sections within a section , and add once again adding sub-subsection under that section. How to make a table structure for that, any idea please Thanks, Hi, I use this code (found in post http://www.phpfreaks.com/forums/index.php?topic=205633.0) to create a tree structure of categories and subgategories. Code: [Select] $prevcat = ''; $prevsubcat = ''; $sql = "SELECT * FROM $tbl_name ORDER BY categ, subcateg"; $result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR); while($row = mysql_fetch_assoc($result)) { $cat = $row['categ']; $subcat = $row['subcateg']; $item = $row['itemname']; $description = $row['itemdesc']; if($cat != $prevcat){ echo $cat.'<br />'; echo 'sc '. $subcat.'<br />';//if the category has changed, we also want to show the new subcat }elseif($subcat != $prevsubcat){ echo $subcat.'<br />'; } echo 'it '.$item.'<br />'; echo 'desc '.$description.'<br />'; $prevcat = $cat; $prevsubcat = $subcat; } The above code works fine but I am trying to figure out how to count results of the deepest subcategory, so I will be able to change cell color or have results presented in two colums (left and right). Example: - main category 1 -- subcategory under category 1 ------ result 1 ------ result 2 ------ result 3 - main category 2 -- subcategory under category 2 ------ result 1 ------ result 2 - main category 3 -- subcategory under category 3 ------ result 1 ------ result 2 ------ result 3 ------ result 4 etc I want to count results under each subcategory, so on the above example I should have: 3 results for category 1 2 results for category 2 4 results for category 3 Any suggestions? Thank you. This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=347192.0 I am working on a script for a simple form with only 2 options that are dropdowns. I need to validate these two options that there is a selection made. I have gotten the first one to validate, but I cannot get the second one to validate. Can anyone steer me in the right direciton why only one is working? I get no errors in the script, so I assume I am just missing something. Code: [Select] <?php // options for drop-down menu $choices = array('-- Choose Your Item','Anniversary Jacket', 'Anniversary T-Shirt'); $sizes = array('-- Choose Your Size','L', 'XL'); if($_SERVER['REQUEST_METHOD'] == 'GET'){ // display form when GET showForm(array()); } else{ // process form if POST $errors = validateForm(); if(count($errors)) showForm($errors); // if errors show again else print 'Form submitted succesfully!'; // no errors } // function generating form function showForm($errors){ global $choices,$sizes; // set defaults $defaults = array(); foreach($choices as $key => $choice){ if(isset($_POST['item']) && ($_POST['item'] == $key)) $defaults['item'][$key] = 'selected'; else $defaults['item'][$choice] = ''; } foreach($sizes as $key => $size){ if(isset($_POST['size']) && ($_POST['size'] == $key)) $defaults['size'][$key] = 'selected'; else $defaults['size'][$size] = ''; } // print form print "<form action='{$_SERVER['SCRIPT_NAME']}' method='post'>"; print "<div>"; print "<select name='item'>"; foreach($choices as $key => $choice){ print "<option value='{$key}' {$defaults['item'][$key]}>{$choice}</option>"; } print "</select>"; showError('item', $errors); print "</div>"; print "<div>"; print "<select name='size'>"; foreach($sizes as $key => $size){ print "<option value='{$key}' {$defaults['size'][$key]}>{$size}</option>"; } print "</select>"; showError('size', $errors); print "</div>"; print "<input type='submit'/>"; print "</form>"; } // display error function showError($type, $errors){ if(isset($errors[$type])) print "<b>{$errors[$type]}</b>"; } // validate data function validateForm(){ global $choices,$sizes; // start validation and store errors $error = array(); // validate drop-down if(!(isset($_POST['item']) && (array_key_exists($_POST['item'], $choices)) && $_POST['item'] != 0)) $errors['item'] = 'Select Item'; return $errors; // validate drop-down if(!(isset($_POST['size']) && (array_key_exists($_POST['size'], $choices)) && $_POST['size'] != 0)) $errors['size'] = 'Select Size'; return $errors; } ?> Hi, I'm hoping someone can lead me in the right direction here. I'm creating a simple shopping cart that I will later pass on to Paypal for payment but my problem is, it won't add the items to my shopping cart when I click add to cart. My products are on different pages and I'm not sure if that is going to matter. When I click "add to cart" nothing gets added and it says my cart is empty. I have two tables with the following columns: 1. products: productId productName productDesc productPrice link (for dynamically creating the page links on the main product page) 2. productscents scentId scentName scentDesc Here is the add code that is in my first products page (Elite Hand Cream): Code: [Select] <?php if(isset($_GET['action']) && $_GET['action'] == "add") { $id = intval($_GET['id']); $desc=intval($_GET['desc']); if (isset($_SESSION['cart'][$id])) { $_SESSION['cart'][$id]['quantity']++; } else { $sql3 = "SELECT * FROM products WHERE productId=[$id]"; $sql4= "SELECT * FROM productscents WHERE scentId=[$desc]"; $query3 = mysql_query($sql3); $query4 = mysql_query($sql4); if(mysql_num_rows($query3) != 0) { $row3 = mysql_fetch_array($query3); $row4 = mysql_fetch_array($query4); $_SESSION['cart'][$row3['productId']] = array("quantity" => 1, "price" => $row3['productPrice'], "desc" => $row4['scentId']); } } } ?> Here is code I have for the $_SESSION: Code: [Select] <?php if(isset($_SESSION['cart'])) { $sql5= "SELECT * FROM products,productscents WHERE productId IN ("; foreach($_SESSION['cart'] as $id => $value) { $sql5 .= $id . ","; } $sql5 = substr($sql,0,-1) . ") ORDER BY productId, scentId ASC"; $query = mysql_query($sql5); if(!empty($query)) { while($row = mysql_fetch_assoc($query)) { ?> <?php echo $row['productName'];?><?php $_SESSION['cart'][$row['productId']]['quantity'];?> <?php } } else { echo "You need to add an item to your cart";} } Here is the code that I have for the "add to cart" and "view cart": Code: [Select] <a href=#&action=add&id=<?php echo $prodId;?>&desc=<?php echo $scent_id[$y];?>>Add to Cart</a><br><a href="cart.php">View Cart</a> This grabs the correct product Id and scent Id which I want and no errors are being displayed on the page. I'm not sure where to begin with this. LOL. I'm new to PHP and I used a tutorial to help with the code. Any help would be greatly appreciated. i have this while loop making my category links at the top of my page, but i still have the bullet after the last item. ive looked at other examples and CANNOT get mine to follow suit...help please? Code: [Select] $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $query1 = "SELECT * FROM ob_category"; $data1 = mysqli_query($dbc, $query1); while($row=mysqli_fetch_array($data1)){ echo '<a href="viewlistings.php">' . $row['name'] . '</a> • '; } I am unsure of how to select something made up of a composite key. Allow me describe the entity... Event ShowID (pk) VenueID (pk) StartDateTime (pk) My Checkout process will have an HTML Table displaying maybe 3-4 different Events like this... Code: [Select] ========================= Register in 3 Easy Steps... Step #1: Select a Date and Attendees Event Ticket (Update) Choose Name Cost Attendees Total One Flower Show $20 ___ $0 <<Buy a Ticket>> Mankato, MN Sept 24, 2011 Flower Show $20 _3_ $60 <<Buy a Ticket>> Willmar, MN Oct 1, 2011 Banjo Jamboree $50 ___ $0 <<Buy a Ticket>> Brainerd, MN Oct 8, 2011 ========================= When a User clicks on a particular "Buy a Ticket" button, how do I capture the 3 Composite Key Values I need so I can insert them into my Order table? Maybe a better question to ask, is HOW/WHERE would I store the 3 Composite Key Values so that when a User clicks on a given "Buy a Ticket" button, that I have the values I need to build my Order record?? Normally with just one value (e.g. Drop-Down List), when someone selects a value, there is a corresponding code that you'd use. For example "Extra Large" in a Drop-Down List equals "3". Hope I'm making sense?! Thanks, Debbie Hi all I am trying to write a piece of code that checks to see if an item is in the SQL database and updates the quantity if it is, or adds it as a new line if it isn't. Here's my code: Code: [Select] if (isset($_GET['add'])) { $id = $_GET['id']; $qty = $_GET['qty']; $date = date ('D M j G:i:s'); $sql_products = mysql_query("SELECT * FROM `items` WHERE `id` = '".$id."'"); $result_products = mysql_fetch_array($sql_products); $product_title = $result_products['title']; $product_price = $result_products['price']; $sql_inbasket = mysql_query("SELECT * FROM `store_basket` WHERE `id` = '".$id."' AND sessionid = '".$sessionid."'"); $isiteminbasket = mysql_num_rows($sql_inbasket); if ($isiteminbasket == 0) { mysql_query ("INSERT INTO `store_basket` SET sessionid = '".$sessionid."', productid = '".$id."', item = '".$product_title."', qty = '".$qty."', price = '".$product_price."', date = '".$date."'"); header("Location: basket.php"); } else { mysql_query("UPDATE `store_basket` SET qty = qty + 1 WHERE id = '".$id."' AND sessionid = '".$sessionid."'") ; header("Location: basket.php"); } } Every time I try and add the same item to the basket, it adds as a new line instead of updating the existing line. Many thanks for your help! Pete Hi, I have some code to help me keep track of the programs that I write for athletes. It is basically a traffic light system, where if an athlete's program does not need to be updated for more than a week, the cell background is green, if it needs to be updated in less than a week, it turns amber, and if it is overdue, it turns red. However, the problem is that when I upload a new program, that row appears in green, but the old program can be seen in red. Basically I want the code to only show the most recent program for each athlete. Not sure if I use Max? for this. I'm looking for the most recent instance of athlete_id_prog in the programs_for_athletes table. Here's the relevant code: Code: [Select] <?php $sql = mysql_query("SELECT * FROM t_athletes, programs_for_athletes WHERE athlete_id = athlete_id_prog and next_prog_completed='No' ORDER BY $field $sort"); echo "<table border='1' align='center' bordercolor='#000000' CELLPADDING=5 cellspacing='0' STYLE='font-size:13px'>"; echo "<tr bgcolor='#000000'> <td>*</td><td><H3><font color='white'>First name</font> $srt[1]</h3></td> <td><H3><font color='white'>Last name</font> $srt[2]</H3></td> <td><H3><font color='white'>Sex</font> $srt[3]</H3></td> <td><H3><font color='white'>Program link</font> $srt[4]</H3></td> <td><H3><font color='white'>Program Expiry Date</font> $srt[5]</H3></td></tr>"; // keeps getting the next row until there are no more to get $row_counter = 1; //create row counter with default value 0 // Print out the contents of each row into a table /*?>$bgColors = array('F'=>'#FF99FF', 'M'=>'#CCCCCC'); while ($row = mysql_fetch_array($sql)) { // Print out the contents of each row into a table echo "<tr bgcolor=\"{$bgColors[$row['sex']]}\">\n"; echo "</td><td>"; echo $row_counter++; echo "</td>"; echo "<td>{$row['firstname']}</td>\n"; echo "<td>{$row['lastname']}</td>\n"; echo "<td>{$row['sex']}</td>\n"; echo "<td>{$row['notes']}</td>\n"; echo "<td>{$row['note_end_date']}</td>\n"; echo "</tr>\n";<?php */ while ($row = mysql_fetch_array($sql)){ if(strtotime($row['prog_expiry_date']) > time()){ // date hasn't expired yet, so we check the remaining days $diff = strtotime($row['prog_expiry_date']) - time(); if($diff <= (60*60*24*7) ){ $bgColors = '#CC6600'; }else{ $bgColors = '#99FF99'; } }else{ // date has expired $bgColors = '#FF3333'; } echo "<tr bgcolor=\"{$bgColors}\">\n"; echo "</td><td>"; echo $row_counter++; echo "</td>"; echo "<td>{$row['firstname']}</td>\n"; echo "<td>{$row['lastname']}</td>\n"; echo "<td>{$row['sex']}</td>\n"; echo "<td>\n"; echo "<a href='http://www.mytestwebsite.com/athlete_programs/" . $row["program_link"] . "' target='_blank'>" . $row["program_link"] . "</a>"; echo "</td>\n"; echo "<td>{$row['prog_expiry_date']}</td>\n"; echo "</tr>\n"; } echo "</table>"; ?> Any advice is much appreciated. Is it possible to add more then one thing in a link? so i can $_GET more then one thing from a link signup.php?state=1?name=sam i tried that and a few other things and it didnt work. Hey all, I'm currently making myself a blog website from scratch. It's sort of my personal project; I'm using it to get a feel for PHP (and it'd look great on my resume!). Anyway, I'm using the following PHP code to get the items from my RSS feed, and display them. Problem is, my first item shows twice! I'm thinking it's a problem with my loop, but I'm not sure. Any ideas: My PHP code to render my RSS is as follows: <?php //Purpose: This loads the XML document using the DOMParser, and mixes it w/ HTML to style and format it. try { $xmldoc = new DOMDocument(); $xmldoc->load('test_RSS_feed.xml'); $content = null; //HTML mixed with XML results go here $allitems = $xmldoc->getElementsByTagName('item'); foreach ($allitems as $item) { //get ALL instances of wanted element(s) $titles = $item->getElementsByTagName('title'); $dates = $item->getElementsByTagName('pubDate'); $descriptions = $item ->getElementsByTagName('description'); //will include the CSS classes for these eventually! $content.= (' <ul class ="blog_entry"> <li class="title_entry"> '.$titles->item(0)->nodeValue. '</li> <li class="date_entry"> '.$dates->item(0)->nodeValue. '</li> <br> <li class="description_entry"> '.$descriptions->item(0)->nodeValue. '</li> </ul> <br><br><br>'); echo $content; } } catch(Exception $e) { echo $e->getMessage(); } ?> And the XML in my RSS feed is as follows: <?xml version= "1.0" encoding = "UTF-8" ?> <!--Every XML doc starts with this --> <?xml-stylesheet type="text/css" href="sample_xml_css.css" ?> <!--stylesheet for RSS feed--> <rss version = "2.0"> <channel> <!--RSS feed information--> <title>My first RSS feed</title> <description>This is my first foray into RSS. I may use this to create a blog!</description> <lastBuildDate>Mon, Oct. 11, 2010 13:13:26 GMT</lastBuildDate> <!--date format complies to different standards--> <webMaster>mserrano0410@gmail.com</webMaster> <!--has email of webmaster--> <item> <title>My first item; this is the title.</title> <link>http://www.example.com/sample_item.html</link> <!--provides a link to the RSS item; required--> <pubDate>Mon, Oct 11, 2010 13:15:20 GMT</pubDate> <!--Every date complies to formatting standards--> <description>We are now inside of an item; this is a description tag.</description> </item> <item> <title>My second item.</title> <link>http://www.google.com</link> <pubDate>Fri, Oct 15, 2010 23:02:40 GMT</pubDate> <description>This is a second helping of examples biatch!</description> </item> <!--can create as many items as you want, but it MUST have: 1) Title 2) Link to item; when clicked, takes you directly to that item. This is a SEPARATE HTML document! 3) Description --> </channel> </rss> Thanks in advance, Marvin hello, i have this simple problem, how can i point to an item in a menu so that it shows the correct page i'm currently visiting? for example, i have this menu : Code: [Select] <div class="submenu"> <div class="submenu-head">Products</div> <ul> <li class="first-item current"> <a tabindex="1" class="first-item current" href="index.php">Products</a> </li> <li> <a tabindex="1" href="add_product.php"> Add new Product </a> </li> </ul> </div> where class="first-item current" points to the current page i'm visiting (i.e Products is highlited) so when i visit another page (add_product.php) i want to do this Code: [Select] <div class="submenu"> <div class="submenu-head">Products</div> <ul> <li > <a tabindex="1" href="index.php">Products</a> </li> <li class="first-item current"> <a tabindex="1" class="first-item current" href="add_product.php"> Add new Product </a> </li> </ul> </div> the usual way i solve this problem is by using a switch statement Code: [Select] switch($header_title) { case "index": echo "<div class="submenu"> <div class="submenu-head">Products</div> <ul> <li class="first-item current"> <a tabindex="1" class="first-item current" href="index.php">Products</a> </li> <li> <a tabindex="1" href="add_product.php"> Add new Product </a> </li> </ul> </div>"; break; switch "add_product": echo "<div class="submenu"> <div class="submenu-head">Products</div> <ul> <li > <a tabindex="1" href="index.php">Products</a> </li> <li class="first-item current"> <a tabindex="1" class="first-item current" href="add_product.php"> Add new Product </a> </li> </ul> </div>"; break} but this is not very efficient, cause if have 10 menu links i would have to write 10 cases so how can u do this without having to write all those cases, like maybe use a function instead?? Hi all I am trying to write a piece of code that cheks to see if an item is in the SQL databse and updates the quantity if it is, or adds it as a new line if it isn't. Here's my code: Code: [Select] if (isset($_GET['add'])) { $id = $_GET['id']; $qty = $_GET['qty']; $date = date ('D M j G:i:s'); $sql_products = mysql_query("SELECT * FROM `items` WHERE `id` = '".$id."'"); $result_products = mysql_fetch_array($sql_products); $product_title = $result_products['title']; $product_price = $result_products['price']; $sql_inbasket = mysql_query("SELECT * FROM `store_basket` WHERE `id` = '".$id."' AND sessionid = '".$sessionid."'"); $isiteminbasket = mysql_num_rows($sql_inbasket); if ($isiteminbasket == 0) { mysql_query ("INSERT INTO `store_basket` SET sessionid = '".$sessionid."', productid = '".$id."', item = '".$product_title."', qty = '".$qty."', price = '".$product_price."', date = '".$date."'"); header("Location: basket.php"); } else { mysql_query("UPDATE `store_basket` SET qty = qty + 1 WHERE id = '".$id."' AND sessionid = '".$sessionid."'") ; header("Location: basket.php"); } } Every time I try and add the same item to the basket, it adds as a new line instead of updating the existing line. Many thanks for your help! Pete Hi, I have an array of items and I randomly want to remove one from the array. What's the easiest way to go about this? I have a php form which shows all comments of the webpage stored in the database. When i click on the edit button the corresponding 'comments' datas should appear in the textarea. how can i do this, pasting my piece of code $query="select *from comments order by id desc"; $result=mysql_query($query); echo "<table width='700' align='center' border=1><tr bgcolor='green' align='center'><td><font color='black'> SlNo </font></td><td><font color='black'>Comment</font></td><td><font color='black'> Date Posted </font></td><td>Edit/Delete</td></tr></b>"; while($row = mysql_fetch_row($result)) { $d=$row['0']; $id=$row['0']; $name=$row['1']; $date_uploaded=$row['2']; echo "<td>$id</td><td>$name</td>". "<td>$date_uploaded</td>". "<td><a href='edit_comments.php?id=$id'>Edit </a></td>". "</tr>"; } echo "</table>"; } if(isset($_GET['id'])) { $id = $_GET['id']; mysql_connect('localhost','root','') or die("Cannot connect to the Host"); mysql_select_db('sample') or die("Cannot connect to the Database !!"); $query = "SELECT comments FROM comments_tble WHERE id = '$id' "; $result = mysql_query($query); $row=mysql_fetch_row($result); echo"<input type='text' col id='edit_comments' value='$row[0]' width='250' height='10' >"; exit; } Say i have an array (called $myarray) and it has 10 numbers in it like this... 1 2 4 8 9 10 12 14 15 18 Now in my code, I get a number and lets say for this example it is "5". I need to see if that number is in the array --easy enough using in_array()--, but if it is NOT in the array, I need to find the next available number in the array that is greater than my starting number of 5 (which would be "8" in this example). But what is the best way to find this number (i.e. 8 in this example)? I imagine I need to somehow loop through but i'm not sure which loop is the best to use and i'm generally confusing the hell out of myself (which is frustrating because this is probably rather simple to do ). Can anyone help guide me in the right direction? |