PHP - Excluding A Category From A List
Hi Guys,
I've been using PHP for a few years now but for some reason I can never seem to get my head around arrays, basically I have a blog site that I want to show all posts that have been posted in public categories but ignore those in the private categories, I had the idea to put all the private category ID's into an array and use that to check against the posts, however my array isn't working out the way I'd hoped. This is what I have: $isPrivate = mysql_query("SELECT categoryID FROM mod_cat WHERE isPrivate =1") or die (mysql_error()); while ($isPrivateList = mysql_fetch_array($isPrivate, MYSQL_NUM)) { $ignoreList = $isPrivateList; } However this isn't working at all. I know its wrong I just can't work out how to make it right. This is the mySQL I want to use it with: mysql_query("SELECT COUNT(*) AS total_entries FROM mod_posts WHERE articlePosted =1 AND articleCat != $ignorelist") Could anyone please help me? Thanks in advance. Similar TutorialsHi friends, I have two mysql db tables, photos and album, I would like to list photos by album how do i do that ? CREATE TABLE `album` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `album_name` varchar(95) NOT NULL, `album_desc` text NOT NULL, PRIMARY KEY (`id`) ); CREATE TABLE `photos` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `album_id` int(11) NOT NULL, `thumb_name` varchar(255) NOT NULL, `photo_name` varchar(250) NOT NULL, PRIMARY KEY (`id`) ) Hello everyone, I am currently working on the script taken from www.phpwebcommerce.com I am only a beginner and have been using it in a little project for an online game just to help my mates be able to trade items and such. I have managed to get almost everything sorted apart from one thing. The function which gets the categories for a drop down select box: Code: [Select] /* Generate combo box options containing the categories we have. if $catId is set then that category is selected */ function buildCategoryOptions($catId = 0) { $sql = "SELECT cat_id, cat_parent_id, cat_name FROM tbl_category ORDER BY cat_id"; $result = dbQuery($sql) or die('Cannot get Product. ' . mysql_error()); $categories = array(); while($row = dbFetchArray($result)) { list($id, $parentId, $name) = $row; if ($parentId == 0) { // we create a new array for each top level categories $categories[$id] = array('name' => $name, 'children' => array()); } else { // the child categories are put int the parent category's array $categories[$parentId]['children'][] = array('id' => $id, 'name' => $name); } } // build combo box options $list = ''; foreach ($categories as $key => $value) { $name = $value['name']; $children = $value['children']; $list .= "<optgroup label=\"$name\">"; foreach ($children as $child) { $list .= "<option value=\"{$child['id']}\""; if ($child['id'] == $catId) { $list.= " selected"; } $list .= ">{$child['name']}</option>\r\n"; } $list .= "</optgroup>"; } return $list; } Basically the problem is that it only creates a category list of two levels e.g. Parent Child and I wish to be able to have more sub categories e.g. Parent Child Child Child Is there anyway of adapting this code so it can do something like that? Many thanks for any help. Hope someone here can help me. Ive been commissioned to convert a template to wordpress that includes a portfolio... I built a portfolio page from a custom post type. that works. Items are categorized with a custom taxonomy named port_cats. that works also On the portfolio page, there is tabbed content built with jquery to show and hide items by category. So theres a category nav menu, plus each item wrapped in classes to show and hide. Im stuck on plugging this in correctly, and am SO CLOSE. I have the category nav list working, but having trouble getting worpress to read the correct category slug inside the loop. Heres how the jquery needs to work: for the menu: Code: [Select] <li><a href="#" rel="category-slug">Category Name</a></li> to hide and show the items: Code: [Select] <ul> <li class="category-slug"> title/thumb/content </li> </ul> Heres my code: Code: [Select] <ul class="select"> <?php //list custom portfolio categories $taxonomy = 'port_cats'; // define portfolio categories from taxonomies in functions.php $tax_terms = get_terms($taxonomy); foreach ($tax_terms as $tax_term) { echo '<li><a href="#" rel="' . $tax_term->slug . '">' . $tax_term->name.'</a></li>'; } ?> </ul> <ul class="display"> <?php // ADD PORTFOLIO $loop = new WP_Query(array('post_type' => 'portfolio', 'posts_per_page' => 6)); while ( $loop->have_posts() ) : $loop->the_post(); $custom = get_post_custom($post->ID); $screenshot_url = $custom["screenshot_url"][0]; $website_url = $custom["website_url"][0]; ?> <li class="<?php echo $tax_term->slug; ?> "> <a href="<?=$website_url?>"><?php the_post_thumbnail(); ?></a> <?php the_title(); ?> <?php the_content(); ?> <a href="<?=$website_url?>Learn more</a> </li> <?php endwhile; ?> </ul> Whats happening is that worpdress is repeating the last category slug on every display item... can anyone tell me what i have wrong here??? THANK YOU! Trisha Hello, I have been searching and trying all sorts of ways to get my sub categories drop down to show the correct info after selecting a category from the main drop down but im getting stuck. It's pulling the categories and sub categories from the mysql database fine but no matter which main category i pick it keeps showing the same result in the sub category. My brother said i need to use some sort of onchange do this so the sub category list refreshs but everything i have tried doesn't work.. PLEASE could some one help. MANY MANY THANKS This is the category form Code: [Select] <select name="job_cats" style="width:165px"> <?PHP $query1 = "SELECT * FROM job_cats"; $result1 = mysql_query($query1) or die ("query 1 failed"); $count1 = mysql_num_rows($result1); for ($i = 0; $i < $count1; $i++) { $row1 = mysql_fetch_array($result1); $job_cats_title1 = $row1['title']; $job_cats_id1 = $row1['id']; echo '<option value="'.$job_cats_id1.'">'.$job_cats_title1.'</option>'; echo $job_cats_id1; } ?> </select> this would echo this in the main category list: cat1 cat2 cat3 cat4 this is the sub category form Code: [Select] <select name="job_sub_cats" style="width:165px"> <?PHP $query1 = "SELECT * FROM job_sub_cats WHERE job_cats_id = $job_cats_id1"; $result1 = mysql_query($query1) or die ("query 1 failed"); $count1 = mysql_num_rows($result1); for ($i = 0; $i < $count1; $i++) { $row1 = mysql_fetch_array($result1); $sub_cats_id1 = $row1['id']; $sub_cats_title1 = $row1['subTitle']; $cats_id1 = $row1['job_cats_id']; echo '<option value="'.$sub_cats_id1.'">'.$cats_id1.'</option>'; } ?> </select> this should echo this: 1 2 3 4 but it keeps echoing just the number 4. THANKS PLEASE HELP ricky My application displays posts based on currentness and popularity, in two distinct lists. Users can also vote on posts, after which they are hidden. The post IDs that users have voted on are stored in a cookie. I need to construct a concise query that prevents "popular" posts and posts that have been voted on from appearing within the "new" list. In my current system, the used values are explicitly excluded from appearing in the query with some very inelegant code. $num_posts = 5; $sql = "SELECT * FROM posts ORDER BY popularity LIMIT ".$num_posts; $query = mysql_query($sql); $excluded_ids = array() while($row = mysql_fetch_assoc($query)) { // ...do some stuff... $excluded_ids[] = $row['post_id']; } if(!empty($_COOKIE['voted_on'])) { // example value "12|19|23|26" foreach(explode("|", $_COOKIE['voted_on']) as $val)) { $excluded_ids[] = $val; } } $sql = SELECT * FROM posts WHERE post_id <>"; $num_excluded_ids = count($excluded_ids); $i = 0; foreach($excluded_ids as $val) { $i++; $sql .= $val; if($i <= $num_excluded_ids) { $sql .= " AND post_id <> "; } } $sql .= " ORDER BY date_posted LIMIT ".$num_posts; $query = mysql_query($sql) // ... This method is ugly and probably very slow. What would be a better approach? Thanks in advance for anything you can suggest. Lets say I have an array of different values... for example, $alreadyViewed = array("hi.jpg","cow.jpg","dog.png"); Lets say my database contains: Code: [Select] animals.jpg cat.jpg cow.jpg hi.jpg dog.png How do you I tell MySQL to only fetch the remaining entries? And ignore everything in the $alreadyViewed array? Hi, I'm sorry to bother you with this request for help. I bought a XML driven Flash website template with an integrated contact form. Even though the contact.php seems pretty secure I receive emails telling me that someone tried to send emails but they contained no recipient addresses, and therefore no delivery could be attempted. So far, it seems as if the validation process in the php and preg_match command seem to work. Never the less those messages keep getting on my nerve. The Failed delivery emails I get look like this: ---------- Date: Mon, 20 Dec 2010 08:12:09 +0100 Message-Id: <E1PUZuj-0005zp-8c@mydomain.com> To: Subject: X-PHP-Script: www.mydomain.com/contact.php MIME-Version: 1.0 Content-type: text/html; charset=windows-1251 From: ---------- As you can see spam protection by filtering the email characters with preg_match has its limits too. The interesting thing is that the sender (E1PUZuj-0005zp-8c) is (of course) changing but only in the last digits. I received about 200 emails with exact the same beginning. So the bot seems to follow an ongoing pattern. I wonder now, if there is a way to set a command to exclude (or to preg_match the exact) character combinations like "E1PUZ" which lead to not sending the email? I know ... it is only a matter of time till the combinations are different but altering the php code once a month is not as much work as deleting all those failed delivery messages per day. When I run this query to exclude records where id = $userarray['id'], $q = "SELECT * FROM users WHERE inst_id = '". $userarray['inst_id'] ."' AND id != '". $userarray['id'] ."' "; it actually ONLY returns records with $userarray['id'] as opposed to excluding them. Isn't the way to exclude them to use != ? I was just wondering if this is a way that you can exclude certain rows from a MySQL query. For example if I have 10 records each with a unique id, is there anyway I can get all of the records except record 5? Thanks for any help. So I have this code: Code: [Select] $skill_query = mysql_query("SELECT * FROM character_stats ORDER BY character_stats.". $fields[$skill] ." DESC LIMIT 0, $end", $c2) or print(mysql_error()); $user_query = mysql_query("SELECT user.username, user.userid, character_stats.uid FROM user, character_stats WHERE character_stats.uid = user.userid ORDER BY character_stats.". $fields[$skill] ." DESC LIMIT 0, $end") or print(mysql_error()); //WHERE user.usergroupid != 6 AND characters.banned = 0 $rank = 1; while($player = mysql_fetch_array($skill_query)){ if($user['userid'] != 1){ continue; } $user = mysql_fetch_array($user_query); if($rank >= $start) output($rank, $user['username'], $user['userid'], $player['combat'], $level, number_format($exp)); $rank++; } Yet for some reason it doesn't work. I know that the Code: [Select] if($user['userid'] != 1){ continue; }Is the reason, but how do I fix it? Basically, my goal is to display these highscores, but omit UserID 1. Thanks. Hi Everyone, I have a rather stupid question, but I haven't been able to find the correct method / syntax to do this. I want to allow users to upload a maximum of 5 photos - less then 5 is OK too. I've been testing the following script and haven't gotten it to ignore error # 4 (no file uploaded): Code: [Select] if ($_FILES['userfile']['error'] == 1 || 2 || 3 || 6 || 7) { echo 'Problem: '; switch ($_FILES['userfile']['error']) { case 1: echo 'File exceeded upload_max_filesize'; break; case 2: echo 'File exceeded max_file_size'; break; case 3: echo 'File only partially uploaded'; break; case 6: echo 'Cannot upload file: No temp directory specified.'; break; case 7: echo 'Upload failed: Cannot write to disk.'; break; } exit; } I will be using a while loop and incrementing through the script (this is simpler version). Does anyone know the proper syntax for the IF statement ' if ($_FILES['userfile']['error'] == 1 || 2 || 3 || 6 || 7)" ? Thanks much, Rick Hello, I need to hide products with same title from WooCommerce shop page and i'm trying to achieve that with a custom loop. For example i have 5 products called "Plex" and the only diferrence between them is the SKU field and the color. I don't care which of the same product will be displayed in the shop page, i just want to display only one of all these products. I created a loop which is working and does hide products with same name but i have a problem. If i set posts_per_page=8 it shows less because it counts the hidden products also. $args = array( 'post_type' => 'product', 'posts_per_page' => 8 ); $query = new WP_Query($args); $list = array(); while ($query->have_posts()) : $query->the_post(); if(in_array(get_the_title(), $list)){ continue; } $list[] = get_the_title(); ?> <li><?php wc_get_template_part( 'content', 'product' ); ?></li> <?php endwhile; wp_reset_postdata(); P.S. I don't want to remove these products, i just want to hide them from shop loop! Any ideas what is the problem with the loop? Is there a better way to achieve that? I must be brain dead...I've searched everywhere and can't seem to find a snippet for this. I'm just looking for some code to show a directory listing, but only certain files (by extension) and I don't want to show any sub-directories. I thought I might have been able to do this in the .htaccess file, but I can't find anything that will get rid of the sub-directories. So, I figure there must be a way to get a file listing, check the extension, add it to the page, or skip it if it's a sub-directory or doesn't match the extension. Or, I could just be totally, way off...anyway, any help would be greatly appreciated...I'm fairly new to php. I have the following result that I am getting from a source. Code: [Select] SimpleXMLElement Object ( [CategoryID] => 1 [Name] => Other [Order] => 0 [link] => http://www.link.com?sub=1 ) SimpleXMLElement Object ( [CategoryID] => 1233916011 [Name] => ceramic [Order] => 1 [ChildCategory] => SimpleXMLElement Object ( [CategoryID] => 1234016011 [Name] => dish [Order] => 1 ) [link] => http://www.link.com?sub=13476 ) SimpleXMLElement Object ( [CategoryID] => 1233917011 [Name] => laminate [Order] => 2 [link] => http://www.link.com?sub=98247 ) I need to get it into a database with the following structure Code: [Select] id categoryID cName cOrder clink cparent By using Code: [Select] foreach($this->resp->Store->CustomCategories->CustomCategory as $cat) { $sub = $cat->CategoryID; $ord = $cat->Order; $linkto = "$stlink?fsub=$fsub"; $nm = htmlspecialchars($cat->Name); $par=$cat->ChildCategory->Order; $query = "INSERT INTO Cat (categoryID,cName,cOrder,clink,cparent) VALUES ('$sub','$nm','$ord','$linkto','$par')"; $result = @mysql_query ($query); // Run the query. } I can get Code: [Select] id categoryID cName cOrder clink cparent 1 1 Other 0 http://www.link.com?sub=1 0 2 1233916011 ceramic 1 http://www.link.com?sub=13476 0 2 1233917011 laminate 2 http://www.link.com?sub=98247 0 But I need to get the ChildCategory in there w/ cparent like Code: [Select] id categoryID cName cOrder clink cparent 1 1 Other 0 http://www.link.com?sub=1 0 2 1233916011 ceramic 1 http://www.link.com?sub=13476 0 3 1234016011 dish 1 1 <--- like this 4 1233917011 laminate 2 http://www.link.com?sub=98247 0 any help appreciated... Hope I am in the right area. I am working on a project which is sort of a business directory. I have a category table, a sub-category table then the actual account table. So a user clicks on the category, then selects the sub-category to view information of accounts in that category, and then be able to click to see the full profile. Here's where I am getting stuck. A user may be listed in more than one sub. As an example, let's say a parent is Cars, then subs might be New, Used, Parts, etc. Now a particular user might be listed under all three subs. How can I link them? I have my cat/sub linked via parent/child id's. However, how can I get the user to be linked to multiple subs? Would I need to create a separate table to do similar to parent/child of the categories? If so, then how would I insert the multiple id's into the table? I assume at this point that I would use drop downs for the subs. I am having a real hard time wrapping my head around this so any help is greatly appreciated. So I am having some difficulties with a category system. I want my code to search the database an unlimited amount of times to the very last directory and then display it in tree view on my screen. I'm having some trouble because I am having to specify how many depths the code will search. How can I get it to do this on it's own? Currently my code does this... <?php // Establish SQL Connection. $mysqli = mysqli_connect( $sql['host'], $sql['user'], $sql['pass'], $sql['db'] ) or die( "DARN"); $query = $mysqli->query( "SELECT * FROM folders ORDER BY name ASC" ); $num_rows = $query->num_rows; echo "Found <b>" . $num_rows . "</b> row(s) in the database!<br>"; while ( $row = mysqli_fetch_array( $query ) ) { // DO NOT REMOVE $id = $row['id']; $name = $row['name']; $parent = $row['parent']; /***************************************************************************************************/ if ( $parent == 0 ) { echo $id . " " . $name . " " . $parent . "<br>"; $query2 = $mysqli->query( "SELECT * FROM folders WHERE parent = " . $id . " ORDER BY name ASC" ); while ( $row2 = mysqli_fetch_array( $query2 ) ) { echo " " . $row2['name'] . "<br>"; } } } ?>I know it's messy, doing the best I can. DB looks a little like this... +----+---------+--------+ An array of "categories" is given: $categories = array( array("id" => 1, "title" => "Pants", "children" => array( array("id" => 2, "title" => "Boots", "children" => array( array("id" => 3, "title" => "Leather"), array("id" => 4, "title" => "Textile"), ), ), array("id" => 5, "title" => "Sneakers"), ), ), array( "id" => 6, "title" => "Sort", "children" => array( array( "id" => 7, "title" => "Balls", ), ), ), );
I need to write a function searchCategory ($categories, $id) that returns the name of the category by the category ID. I have created a form which allows people to add data to a database. However, I want to replicate the form across several pages and give each page a category. For example, if I have a website based on sport. I have a page which enters information into the baseball category, a page which enters information into the ice hockey category, a page which enters information into the soccer category etc. Can someone advise how I would do this? Hi How can i see which category is being used in rss feed, this is my code to parse one rss feed. $feed_url = "http://www.foo.com/feed/"; $xml = simplexml_load_file($feed_url); foreach ($xml->channel->item as $item) { $ns_content = $item->children('http://purl.org/rss/1.0/modules/content/'); $title = $item->title; // This is title $desc = $ns_content->encoded; // This is description $category =""; // Here i am stuck, how can i get category associated with this feed } How can i see its category, i see in source code it looks like this and even categories have sub categories which looks same, i wants categories names to display wihich is associated with feed: <category><![CDATA[Health]]></category> <category><![CDATA[Men]]></category> thanks for any help. |