PHP - Fetch Categories And Get Their Last Article In Same Query
I am developing a CMS with articles and categories. I am making a feature for the admin panel that shows all the categories. In the table, I would like to include each category's latest article. My traditional method is to select just the categories in one query, loop through the results, and then inside the category loop have a query that gets the information on the latest article... So something like...
$query = " SELECT category_id, title, description FROM categories ORDER BY title ASC"; if($query = mysql_query($query)){ while($cat=mysql_fetch_assoc($query)){ $query_article = " SELECT article_id, category_id, title FROM articles WHERE category_id = ".$cat['category_id']." ORDER BY article_id DESC LIMIT 1"; $last = mysql_fetch_assoc($query_article); } }How could I use joins and/or subqueries to achieve my goal of combining these two queries into one? I have come up with a query which is below: SELECT c.category_id, c.title, c.description, a.article_id, a.category_id, a.title, COUNT(a.article_id) AS total_articles FROM article_categories AS c LEFT JOIN articles AS l ON ( SELECT article_id AS article_id, category_id, title AS article_title FROM articles AS l WHERE l.category_id = c.category_id ORDER BY l.article_id DESC LIMIT 1) LEFT JOIN articles AS a ON (c.category_id = a.category_id) GROUP BY c.category_id ORDER BY c.title ASCWhen I use the above query, I get an error saying "Operand should contain 1 column(s)" I would also like to add something that counts the total number of articles in the category. Thanks for your time! Similar TutorialsHi all am haiving abit of a problem am trying to query 6 categories with 6 games each.With the code i done is only showing one cat with 6 games.
How can i fix this ?.
If you go to games-flash.co.uk you will see at the bottom of the home page that only one cat shows.
php code.
<div class="catgames"> Hello Guys, Need a little help here. I have a db structure like this cat_id | cat_name | cat_status | parent_id 1 First Test 1 0 2 Just testing 1 0 4 Books 1 2 5 Cars 1 0 6 Ford 1 5 If the parent_id = 0 it is considered to be the parent. If it is a number it is considered a child and referencing the parent I want to be able to query the database and grab the cat and the sub cat and echo it on my page. Its like a classified ads application. Here is my while loop that I currently have which only echo's out the parent category. I would like to echo the child category under the respective parent category. I think I would have to do a loop within a loop, but not sure how to do it.. $query = "SELECT * FROM ad_category WHERE cat_status='1' && Parent_id='0' ORDER BY cat_name"; $result = mysql_query($query); while($row = mysql_fetch_row($result)) { $cat_name = $row[1]; $cupper = UCWords($cat_name); echo $cupper . "<br>" ; } Thanks for your help in advance I have been going in circles about how to handle the issue that I have come up with and was hoping that someone could provide a different method. Basically I want to be able to create an infinite number of categories and allow them to be assigned to other categories then making them subcategories/sub sub categories if you will. My initial plan was to use a method I have used before by just saving the parent id of the subcategories and recursively going through the data. However, I am not to fond of this because of the inefficiency that it provides. I did some research and found that method is called the "Adjacency List". I also found another way to do it called "Nested Sets" which seems to be much more efficient but its a little harder to understand / maintain. I was hoping that someone here could offer alternatives to both of these methods that will allow me to keep the efficiency of "Nested Sets" but providing the ease of use / maintenance of the "Adjacency List". Thanks in advance for any help. Hi, Please help I need to make categories with su-categories I made in my database tables like this table = categories cid | cat_id | parent_list | categ_name | type 1 0 1 General category c 2 1 1,2 sub category s 3 1 1,3 sub category s 4 1 1,2 sub category s 5 1 1,5 sub category s 6 5 1,5,6 sub sub category s 7 0 7 General category2 c 8 7 7,8 sub category s I need to view this in dropdown menu using parent_list column Hi All, I have a 'Newspaper' in a game I'm coding. My plan was to have an edition every week and on average 15 articles a week. I would set this out like so. . Code: [Select] <? $select_paper=mysql_query("SELECT * FROM paper WHERE id=1"); while($the=mysql_fetch_object($select_paper)){ ?> <table width=100% class=table> <tr> <td> <td width=50% style=border: none; background-color: transparent; valign=top> <table border=1 cellpadding=0 cellspacing=0 bordercolor=#000000 class='main' align=center> <tr> <td width=500 class='tableheading'><?php echo "$the->title"; ?><center> </center></td> </tr> <tr > <td class="profilerow" align=left><center><?php echo "$the->news"; ?> </td> </tr> <tr > <td class="subtableheader" align=left><center><?php echo "Article By $the->by - $the->date"; ?> </td> </tr> </table> <br> </td> <? } ?> With that repeated for 15 articles per edition. BUT! To save time, space and complication, I would rather do it using something like this. . Code: [Select] $select = mysql_query("SELECT * FROM paper WHERE edition=1 ORDER by id ASC"); $num = mysql_num_rows($select); Could someone tell me how to intergrate this with the layout tables as show in code #1? Thanks! I have a database in which i store articles that contain all type of special characters including slashes, single quotes, double quote etc. Previously it was working fine, but now after the updating the xampp, things are not going as usual. I insert are articles using following code $query = "INSERT INTO `articles` (`source`, `heading`, `description`, `catagory`, `detail`, `date`, `timestamp`) values ('$source', '$heading', '$desc', '$catagory', '$detail', '$date', '$timestamp')"; Error I am getting is Error Running query 1You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's economy and emphasized that international community should provide its complet' at line 2 Can anybody tell me whats wrong with my script? I have manage to create my own script that add news article, however, I would like to add a comment form below the news article. How can I relate the news and the comments? also, when I delete the articles, it should also delete the comments in mysql. Your help is highly appreciated! Hello, can you help me on my news article? I would like to be able to add photo on the article. Below is my codes Quote ======= html ======= <?php include_once ('post_news.php'); ?> <form Action="add_news.php" Method="post"> <input name="postdate" type="text" id="postdate"> <input name="title" type="text" id="title"> <textarea name="newstext" cols="60" rows="15" id="newstext"></textarea> <input type="submit" name="submit" value="Submit"> <input type="reset" name="reset" value="Reset"> </form> ============== php - post_news.php ============== <?php ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); if (isset ($_POST['submit'])) { require_once ('inc/dbConfig.php'); // Define the query. $query = "INSERT INTO news (id, postdate, title, newstext) VALUES (0,'{$_POST['postdate']}', '{$_POST['title']}','{$_POST['newstext']}')"; // Execute the query. if (@mysql_query ($query)) { print "<p>Data has been added.</p>"; } else { print "<p>Could add the entry because: <b>" . mysql_error() . "</b>. The query was $query.</p>"; } mysql_close(); } ?> ===== db structure ====== id int(10) unsigned NOT NULL auto_increment, postdate timestamp(14), title varchar(50) NOT NULL, newstext text NOT NULL, PRIMARY KEY (id), KEY postdate (postdate) Hope you guys can help me. Thanks! I'm building an article system, what im trying to do is when a user choose the article to be published tomorrow to able to. Write today the article but the system will show it from tomorrow Code: [Select] $gettoday = date("Y:m:d"); $query = "SELECT * FROM tblnews WHERE MainArticle = 1 AND NewsDate = '".$gettoday."' ORDER BY `Id` DESC LIMIT 1"; $result = mysql_query($query); This is my code, but when i use this and the article is not posted for today is not showing anything.. any suggestions please? Thank you I'm feeling a little overwhelmed/burned-out/confused... I have a page "article_index.php" that contains a summary of each article plus a link to it, e.g. Code: [Select] <a href="<?php echo WEB_ROOT; ?>articles/postage-meters-save-you-money"> When you click on a link, it goes to "article.php" and uses a mod_rewrite to transform the "pretty URL" to regular URL that "article.php" can use to query the correct article from my database. ----- Here is what I need help with... When a user is on a given article page, I want to sto - ReturnToPath - ArticleID in the SESSION. I am drawing a blank on how to get the "ArticleID" when a user is on a give page?! Hope you guys follow me?! Debbie Hello, I am trying to create article directory for learning PHP MySql and i want to write a script for recording number of views for an article and store it in Database. Can anyone please direct me to a nice simple tutorial or help me with the steps or algorithm? Suppose the link for an article is http://www.domain.com/article.php?id=123 Do i need to put extra variables and create a tracking PHP file for it? hi there, basically in my database i have DATETIME for when an article was posted, using this, I'd like to make it possible for viewers of the article to see when it was posted in a "Posted Today", "Posted Yesterday" or Posted 23 hours ago" format. If it was posted longer ago than yesterday, then I would like it to just be the normal date. I know how to work out if it was posted today, just through: $date = date('j F', strtotime($rows['date'])); $today=date('j F'); but not sure how to do the hours. thanks! This topic has been moved to Apache HTTP Server. http://www.phpfreaks.com/forums/index.php?topic=322454.0 Hi all - I'm setting up a custom PHP blog. It pulls the data from a MySQL database which includes HTML tags (<p><div><span> etc...). I would like to display only up to 50 words per post on the blog page, which users can then read and click a link to then see the entire post. I've developed some code which does this, however, it seems to be stripping my HTML tags... Very sad! Would be very very grateful if one (or more) of you kind lot would have a look at my code and let me know if there is a easier (I'm all for easy) and proper way of implementing this so that it works without stripping my HTML tags. Cheers!!! Code: [Select] // Counts number of blog words in the content $blog_content_words = str_word_count($blog["content"], 1); // Sets the blog_words variable to 0 $blog_words = 0; // Prints title on page as a permalink to a post echo '<h1><a href="blog.php?id='.$blog["id"].'">'.$blog["title"].'</a></h1><p>'; // Loops while blog_word is under 50 while($blog_words < 50) { // Prints a word from blog_content_words array of blog post and adds a space afterwards echo $blog_content_words["$blog_words"]." "; // Adds 1 to the blog_words counter ++$blog_words; } // Adds a read more link to the post which links to full blog post echo '... <a href="blog.php?id='.$blog["id"].'">[read more]</a></p>'; i need to submit 1 article (3 input fields: title, category, description), to multiple sites. it must be done with 1 click. one more thing... each site to which i have to submit has different input names, but are the same 3, also 1 is for title 1 for category and 1 for description. I have two tables, one called Categories and one called SubCategories. Each subcategory needs to be displayed under its parent category in a HTML table. So I have this code, but I don't know how to list each Sub-Category under each Category in a HTML table. <?php require ('includes/initialize.php'); require 'classes/database.class.php'; $sql = "SELECT * FROM Categories, SubCategories WHERE Categories.ID = SubCategories.CatID"; $Result = $database->Query($sql); $Data = $database->Fetch($Result); ?> Hello dear friends, If i've the following ( categories - gifts ) <?PHP $sql ="select * from categories"; $result= mysql_query($sql); while($line= mysql_fetch_array($result)){ $qryrow="select * from gifts where gifts='$line[1]'"; } ?> it means select category and its gifts now my question how to view it all in table for example if i add Code: [Select] <TABLE cellSpacing=1 cellPadding=1 width="100%"> <TBODY> <TR> <TD> <?php echo "". $line[1].""; ?> </TD> </TR> </TBODY> </TABLE> it will show me like this How can i make it like this my problem how to make table like this and where to put the php variable .. thanks How can i make unlimited sub categories when i have this mysql fields: id, name, parent Code: [Select] $query = "SELECT * FROM cats"; $result = mysql_query($query); while ($var = mysql_fetch_array($result)) { echo $var['name']; // now i need here some code for sub cats, but sub cat in subcat :( } Can someone help me? Hi there, I have a piece of code that takes all posts with the category of 'model' and puts it on the models page. It then displays the post as a gallery using fancy box. The problem is I want all posts with the category of 'faces' to go on the faces page, but at the moment they are appearing on both pages. Here is the code I have. Any help will guarantee a donation as I am at my wits end trying to figure this out. Code: [Select] <?php global $post; $args = array( 'numberposts' => 8, 'offset' => 0, 'category' => 'models', 'orderby' => 'post_date', 'order' => 'DESC', 'post_type' => 'post', 'post_status' => 'publish' ); $posts_array = get_posts( $args ); $x = 1; // track model foreach( $posts_array as $post ) { setup_postdata($post); ?> <div id="model-thumb"> <?php $arg2 = array( 'post_type' => 'attachment', 'numberposts' => -1, 'order' => 'ASC', 'post_status' => null, 'post_parent' => $post->ID ); $attachments = get_posts($arg2); if ($attachments) { $i = 1; // track images foreach ( $attachments as $attachment ) { $image_attributes = wp_get_attachment_image_src( $attachment->ID, 'full' ); if ($i == 1) { // Get thumbnail info to display with second image $img1src = $image_attributes[0]; $img1w = $image_attributes[1]; $img1h = $image_attributes[2]; } elseif ($i == 2) { // Display thumbnail with link to second image ?> <a class="allModels" rel="gallery<?php echo $x; ?>" href="<?php echo $image_attributes[0]; ?>" ?><img src="<?php echo $img1src; ?>" width="<?php echo $img1w; ?>" height="<?php echo $img1h; ?>"/></a><br /><p><?php the_content();?></p></div> <?php } else { // Other images ?> <div style="display:none;"><a class="allModels" rel="gallery<?php echo $x; ?>" href="<?php echo $image_attributes[0]; ?>"><img src="<?php echo $image_attributes[0]; ?>" width="<?php echo $image_attributes[1]; ?>" height="<?php echo $image_attributes[2]; ?>"/></a></div> <?php } $i++; // Increase image count } } $x++; // Increase model count } ?> |