PHP - Count Results During A Loop
Hello all,
I've built a database of coupons. Each coupon is assigned to a category (so all electronics coupons display under electronics). On my category list I'd like to display how many coupons is in each category. Currently this function displays my category list: function fetch_categories() { mysql_connect(SQL_HOST_NAME, SQL_USER_NAME, SQL_PASSWORD) or die(mysql_error()); mysql_select_db(SQL_DATABASE) or die(mysql_error()); $result = mysql_query("SELECT * FROM categories ORDER BY category_name")or die(mysql_error()); echo '<div id="category_list">'; echo '<ul class="cat_list">'; while($row=mysql_fetch_assoc($result)){ //get total of discounts in each category $count_result = mysql_query("SELECT * FROM category_relations, discounts WHERE category_relations.member_of = '$row[id]' AND discounts.active = '1'")or die(mysql_error()); $num_rows = mysql_num_rows($count_result); echo '<span class="numrows">('.$num_rows.')</span>'; echo '<li><a href="index.php?cat_ID='.$row['id'].'">'.$row['category_name'].' </a></li>'; } echo '</ul>'; echo '</div>'; } The above is a debug version so it's not all formatted correctly. However right now, that exports "3" for Airlines when right now, I have only one discount in the entire database. This is my category_relations table: Code: [Select] -- -- Table structure for table `category_relations` -- CREATE TABLE IF NOT EXISTS `category_relations` ( `id` int(10) NOT NULL, `member_of` int(10) unsigned NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `category_relations` -- INSERT INTO `category_relations` (`id`, `member_of`) VALUES (2, 2), (1, 1), (3, 1), (4, 1); And this is my discounts table: Code: [Select] -- -- Table structure for table `discounts` -- CREATE TABLE IF NOT EXISTS `discounts` ( `id` smallint(5) NOT NULL AUTO_INCREMENT, `redeem` tinyint(3) NOT NULL, `discount_title` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `short_description` tinytext CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `eligibility` blob NOT NULL, `url` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `coupon_code` varchar(75) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `start_date` datetime DEFAULT NULL, `end_date` datetime DEFAULT NULL, `long_description` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `logo` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `business_name` varchar(75) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `phone` varchar(80) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `store_location_street` varchar(75) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `store_location_city` varchar(75) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `store_location_state` char(2) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `store_location_zip` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `categories` blob NOT NULL, `level` tinyint(5) NOT NULL, `active` tinyint(1) NOT NULL, `user_id` varchar(2555) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`), KEY `level` (`level`,`active`), KEY `user_id` (`user_id`(333)) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ; -- -- Dumping data for table `discounts` -- INSERT INTO `discounts` (`id`, `redeem`, `discount_title`, `short_description`, `eligibility`, `url`, `coupon_code`, `start_date`, `end_date`, `long_description`, `logo`, `business_name`, `phone`, `store_location_street`, `store_location_city`, `store_location_state`, `store_location_zip`, `categories`, `level`, `active`, `user_id`) VALUES (1, 0, '$2.00 Off Transportation', '', 0x4172726179, 'www.baysideshuttle.com', '', '2010-01-01 00:00:00', '2011-01-01 00:00:00', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer varius ipsum id justo pellentesque laoreet. Curabitur tempus tincidunt...', NULL, 'Bayside Airport Shuttle', '850-123-3456', NULL, NULL, NULL, NULL, 0x4172726179, 0, 1, '24'); It seems to be completely ignoring my active check. How can I fix this, or is there a better way to do this query? Similar Tutorialsin my mysql query, after the results have been grouped is there any way to count the results? i have a end result like this: 784 | x.x.x.x 754 | x.x.x.x 784 | x.x.x.x so how can i count the first column after its been grouped by IPs? here is my query: SELECT * FROM `hits`GROUP BY ip I'm trying to make a function which will display the top X results of the row Y which I set, for this instance I'm using the row browser and the top 5 results from my table statistics, the where is just to eliminate Search Bot results from showing up. I also want it to return the count of the amount of rows as well. So say there was 10 results for the browser 'Safari', then it would return the count of 10 for that result as well as the result itself. Code: [Select] $display->show_list('statistics', 'browser', '5', 'WHERE browser!=\'Search Bot\''); Here is my function. I'm cleaned it up a bit to remove certain checks and outputs if the query were to fail, etc. Code: [Select] function show_list($table, $row, $limit = 5, $where = NULL) { $item = mysql_query("SELECT DISTINCT $row FROM $table $where LIMIT $limit"); $result = array(); while ($fetch = mysql_fetch_array($item)) { $result[] = $fetch; } return $result; } Basically, how would I go about making it count the amount of rows for the row I've set, and then to output that along side the result? First up quick thanks in advance, any and all help is greatfully recieved
I have this query:
SELECT Player.MembershipNo , Player.FirstName , Player.LastName , Venue.VenueName as Venue, Results.MemCard, Results.EarlyReg , Position.Points as Venue_Points, Results.Date FROM Position , Player , Results , Venue WHERE Player.MembershipNo =Results.MembershipNo AND Results.Position =Position.Position AND Venue.VenueID =Results.VenueID AND Results.Date BETWEEN '2014-07-01' AND '2014-09-30' ORDER BY MembershipNo, Venuewhich returns these results: +--------------+-----------+----------+-------------------+---------+----------+--------------+------------+ | MembershipNo | FirstName | LastName | Venue | MemCard | EarlyReg | Venue_Points | Date | +--------------+-----------+----------+-------------------+---------+----------+--------------+------------+ | 0 | Bob | Stevens | The Dolphin | 1 | 1 | 32 | 27/08/2014 | | 0 | Bob | Stevens | The Enigma Tavern | 1 | 1 | 40 | 08/07/2014 | | 0 | Bob | Stevens | The Enigma Tavern | 1 | 1 | 16 | 15/07/2014 | | 1 | Dave | Green | The Dolphin | 1 | 1 | 20 | 13/08/2014 | | 1 | Dave | Green | The Dolphin | 1 | 1 | 2 | 20/08/2014 | +--------------+-----------+----------+-------------------+---------+----------+--------------+------------+ I'm getting the number of friends in each STATE. How do I split the results in $returnS? $query = "SELECT statez, COUNT(statez)FROM abs GROUP BY statez"; $results = mysql_query($query); $returnS=""; while($line = mysql_fetch_array($results)) { $returnS.= $line['COUNT(statez)'].",,".$line['statez'].",,,"; } echo $returnS; mysql_close($link); ?> I am working to echo the results in a while or for loop... Both of my sample codes work, but the results are wrong! The while loop ONLY echos a result IF the first record in the postings table matches the id passed (does not display a result unless the first record has a match) The if loop displays ALL listings with the same name (counts them all) so there are no unique listings! <?php $posts_by_city_sql = "SELECT * FROM postings WHERE id='$_GET[id]'"; $posts_by_city_results = (mysqli_query($cxn, $posts_by_city_sql)) or die("Was not able to grab the Postings!"); /* While Loop */ while($posts_by_city_row = mysqli_fetch_array($posts_by_city_results)) { echo "<li><a href='posting_details.php?id=$posts_by_city_row[id]'>$posts_by_city_row[title]</a></li>"; } /* For Loop */ $posts_by_city_row = mysqli_fetch_array($posts_by_city_results); for ($i=0; $i<sizeof($posts_by_city_row); $i++) { echo "<li><a href='posting_details.php?id=$posts_by_city_row[id]'>$posts_by_city_row[title]</a></li>"; } ?> Results with for loop (there are 7 total unique book names, but it's just counting the first match on id 7 times like below): AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners AJAX for Beginners hello, I have a search that matches users ISBN with two databases....code is below $query_search_exact_match = mysql_query("SELECT nvc_site.title, nvc_site.id, nvc_site.description, nvc_site.search_text, nvc_site.image, nvc_site.date, nvc_site.price, nvc_site.location_city, nvc_site_ads_extra.name, nvc_site_ads_extra.value, nvc_site_ads_extra.classified_id FROM nvc_site,nvc_site_ads_extra WHERE name = 'ISBN%3A' AND live=1") or die(mysql_error()); then i take the ISBN that the user entered and match that with the isbn's in the DB while ($fetch_extra = mysql_fetch_array($query_search_exact_match)) { $value = ereg_replace( "[^0-9]", "", $fetch_extra['value'] ); $to_find_isbn = mysql_real_escape_string(ereg_replace( "[^0-9]", "",$_POST['szs'])); if($value == $to_find_isbn) { echo "Match Found"; } else { echo "No Match Found"; } //ELSE doesn't work here.....it displays both the if and else at the same time } i need it to display no match found if there was no match found.....I am soo lost right now!! please help thank you I can't get the COUNT of the matching results? Please help. $SomeVar = myname; $queryU = "SELECT * FROM adxone WHERE username = '".$SomeVar."'"; $resultU = mysql_query($queryU); while($scoreP = mysql_fetch_array($resultU)) { $scoreP['roundzAa']; $scoreP['roundzAb']; $scoreP['roundzAc']; $scoreP['roundzAd']; $scoreP['roundzAe']; $scoreP['roundzAf']; $scoreP['roundzAg']; $scoreP['roundzAh']; } $WinV = 'resultA'; $query = "SELECT * FROM acs WHERE resultx = '".$WinV."'"; $result = mysql_query($query); while($scoreUsr = mysql_fetch_array($result)) { $scoreUsr = $scoreM1['winxa']; $scoreUsr = $scoreM1['winxb']; $scoreUsr = $scoreM1['winxc']; $scoreUsr = $scoreM1['winxd']; $scoreUsr = $scoreM1['winxe']; $scoreUsr = $scoreM1['winxf']; $scoreUsr = $scoreM1['winxg']; $scoreUsr = $scoreM1['winxh']; } $count1 = count( array_intersect($resultU, $result) ); echo($count1); mysql_query("UPDATE comp SET id=$count1 WHERE username = '".$SomeVar."'"); ?> I have this SQL query that gathers set information for the Salesperson($user) that is logged in and viewing theri need information. Everything works weell, except my Loop Count. I don't know, what I am doping incorrectly. It returns only two values which are the same. But the Query returns 10 values for that user. When I run the query direct in SQL DB. What am I missing? Code: [Select] <div class='page_content clearfix'> <div class='grid_8 first'> <?php $salesPersonId = & JFactory::getUser()->get('username'); //$merchantId = JFactory::getSession()->get('merchantId'); $db =& JFactory::getDBO(); $query = " SELECT XXX_merchant.*, XXX_merchant.name as MercName, XXX_merchant.address as MercAddress FROM XXX_sales_person, jXXX_merchant WHERE XXX_sales_person.user_name = '$salesPersonId' AND XXX_merchant.sales_person_id = XXX_sales_person.id"; $db->setQuery( $query ); $row = $db->loadObject(); //echo $query; //echo $query; //echo '<br>'; //echo $salesPerson->name; ?> <?php $link = 'index.php?option=XXX&controller=deal&task=view&id=' . $row->id; $count = 0; foreach ( $row as $row): $link = '/index.php?option=XXX&controller=merchant&task=edit&cid[]=' . $row->id; ?> <div class='quickie_login grid_9 last' style="width: 140px"> <div class='text_center' id='login_banner'> <div class='page_content text_center'> <div class="avatar" style="float: left; margin-top: -10px; padding: 0px;"> <a class="k2Avatar ubAvatar" href="<?php echo $link; ?>" title="<?php echo JText::_($row->MercName); ?> Edit Account" target="_blank"> <span class="ubName" style="display: block; margin-top: -20px;"><b><?php echo $row->MercName; ?></b> </span> <?php if(!empty($row->logo_url)) { $imagePathArr = unserialize(urldecode($row->logo_url)); $link='http://'; $link.= $_SERVER["SERVER_NAME"].$link_server.DS; $link.=$imagePathArr[0]; $link =str_replace("\\","/",$link); ?> <img src='<?php echo $link; ?>' alt="<?php echo $row->name; ?>" style="max-width: 100px; height:100px;"/> <?php } ?> </a> </div> <div class="sales-system2"> <div style="display: block; margin-top: 0px;"> </div> </div> </div> </div> <?php endforeach;?> Basically, this part of the code is checking the "scanned" table in my mysql database to get the last scanned date for the item at hand. It then takes that date and selects all the vendor items in the odbc table "ARVEND" that are greater than the last purchase date. || This is where I am running into a problem. When it loops through each vendor item it selects from the "associated" mysql table to see if the vendor item has been scanned. If it does not find anything I am trying to get the $checkpurdate variable to add 1 to itself. | In the second script you will see the elseif($checkpurdate>0) .... Here I am saying if there are any vendor items that have not been scanned, highlight the row in yellow. But, this part of my code $checkpurdate = $checkpurdate + 1; does not seem to be counting correctly. Sometimes it counts '4' for an item when there are only two vendor items available. All of this may sound confusing since you may not know what I am trying to do. But, the main problem I am having is the counting part is returning wrong numbers. $checkpurdate = $checkpurdate + 1; Code: [Select] /* $checkpurdate */ $query3 = "SELECT date FROM scanned WHERE `item` = '$ITEM' ORDER BY date DESC LIMIT 1"; $result3 = mysql_query($query3); $checklastdate = ""; while($row3 = mysql_fetch_array($result3, MYSQL_ASSOC)) {$checklastdate= $row3['date']; $checklastdate=date("m/d/y", strtotime($checklastdate)); } //checkpurdate loops $checkassoc="0"; $checkpurdate="0"; $sqlc="SELECT RECNO5 FROM ARVEND WHERE PURDATE1 > '$checklastdate' AND ITEM = '$ITEM'"; $rsc=odbc_exec($conn,$sqlc); if (!$rsc) {exit("Error in SQL");} while (odbc_fetch_row($rsc)) { $checkrecno5=odbc_result($rsc,"RECNO5"); $checkassosquery = "associated WHERE `VENDORID` = '$checkrecno5' AND ITEM = '$ITEM'"; $checkassoc = get_rows($checkassosquery); if($checkassoc>0) { // do nothing } else { $checkpurdate = $checkpurdate + 1; } } Code: [Select] elseif($checkpurdate>0) { echo"<TR class=\"NV\"> <TD>"; } Hi I have currently written some code which uses of the Twitter API and extracts the information required to display my most current tweet on my website. This is all working perfectly but at the minute it is only displaying one tweet and I would like it to display as many as the variable $limit is set to. I have tried numerous count with while loops but just cannot seem to get my head around the logic of it. Here is the code im currently using which displays one tweet. <?php $username = "my_twitter_username"; $limit = "2"; $twitter_url = "http://twitter.com/statuses/user_timeline/$username.xml?count=$limit"; $buffer = file_get_contents($twitter_url); $xml = new SimpleXMLElement($buffer); $status_item = $xml -> status; $status_id = $xml -> status -> id; $user_item = $xml -> status -> user; $user_id = $xml -> status -> user -> screen_name; $description = $status_item -> text; $status_time = $status_item -> created_at; $status_img = $user_item -> profile_image_url; $description = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $description); $description = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $description); $description = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $description); $description = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=%23\\1\" target=\"_blank\">#\\1</a>", $description); echo " <div class='tweet-wrapper'> <div class='tweet-img'> <a href='http://www.twitter.com/la__academia' target='_BLANK'><img src='$status_img' alt='La Academia Twitter' style='width:30px height:30px;' /></a> </div><!-- tweet-img --> <div class='tweet-text'> <p class='tweet-p'>$description</p> <p class='tweet-time'>$status_time . <a href='http://twitter.com/?status=@$user_id%20&in_reply_to_status_id=$status_id&in_reply_to=$user_id' target='_BLANK' class='tweet-reply'>Reply</a></p> </div><!-- tweet-text --> <div class='cleaner'></div> </div><!-- tweet-wrapper --> "; ?> Thanks for any help. Hello dear friends, I've made littel code that fetch the categories name from an software website $text= file_get_contents('http://win.softpedia.com/'); // it make win.softpedia as text code $start = strstr("$text",'<ul id="windows_cat">'); // search inside to that start point $end = strpos("$start",'" title="'); // end at it to that end point $cat = substr($start,66,$end-66); echo "$cat<hr>"; it will show now the categories but it only shows the 1st one Antivirus/ how then loop it to find next and next and so on to show me the list of the categories ! thanks Hello, I have a database that contains a column with a int value for number of slots reserved, and what I want to do is fetch the value of each column and add them together to create one whole number. For example, in my database under preserved I have two separate values of 2 and 4.. I would like to take those two values and add them up into 6 through php... here is what I have so far: $slots = mysql_query("SELECT * FROM treservations WHERE reservation_date='$reservation_date' AND reservation_hour='$reservation_hour'") or die(mysql_error()); while ($row = mysql_fetch_assoc($slots)) { $row["preserved"]; } mysql_free_result($slots); Any help would be GREATLY appreciated.. if I need to add additional code please let me know. Thank you! Hi, I'm developing a "gallery" script so that I can manage my photos online, and I'm having a problem I can't seem to figure out. Hoping someone can help... So here's my problem. I have two main tables for my application (amongst several others but for all intents and purposes they aren't needed). One is "albums" and the other "photos". Here's the structure for both: Code: [Select] Albums CREATE TABLE IF NOT EXISTS `kill4silence_photos_albums` ( `id` int(255) NOT NULL AUTO_INCREMENT, `parent_id` int(255) NOT NULL, `user_id` int(255) NOT NULL, `cover` int(255) NOT NULL, `name` varchar(50) NOT NULL, `description` text NOT NULL, `location` varchar(255) NOT NULL, `time` varchar(50) NOT NULL, `date` varchar(50) NOT NULL, `timestamp` int(255) NOT NULL, `last_updated_date` varchar(50) NOT NULL, `last_updated_time` varchar(50) NOT NULL, `last_updated_timestamp` int(255) NOT NULL, `views` int(255) NOT NULL, `tags` longtext NOT NULL, `downloads` int(255) NOT NULL, `download_disabled` int(1) NOT NULL, `comments_disabled` int(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=156 ; ----------------------------------------------------------------------------------------- Photos CREATE TABLE IF NOT EXISTS `kill4silence_photos_photos` ( `id` int(255) NOT NULL AUTO_INCREMENT, `album_id` int(255) NOT NULL, `user_id` int(255) NOT NULL, `name` varchar(50) NOT NULL, `caption` varchar(200) NOT NULL, `time` varchar(50) NOT NULL, `date` varchar(50) NOT NULL, `timestamp` int(255) NOT NULL, `file_name` varchar(5000) NOT NULL, `file_type` varchar(100) NOT NULL, `file_ext` varchar(25) NOT NULL, `location` varchar(200) NOT NULL, `photo_time` varchar(50) NOT NULL, `photo_date` varchar(50) NOT NULL, `views` int(255) NOT NULL, `tags` longtext NOT NULL, `downloads` int(255) NOT NULL, `downloads_disabled` int(1) NOT NULL, `comments_disabled` int(1) NOT NULL, `visible` int(1) NOT NULL, `last_updated_date` varchar(50) NOT NULL, `last_updated_time` varchar(50) NOT NULL, `last_updated_timestamp` int(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=204 ; Now basically how this works is when a new album is created, it is given a parent_id of '0' where the parent_id is the identifer of it's "parent" album. Say, I have five albums, each nested within each other like so. 1, 2, 3, 4, 5. On the page, it would look like, Album 1 (link that takes you to Album 2) Album 2 (link that takes you to Album 3) And so on... I use $_GET to send you to the next nested album. Each album's query string looks like this: Code: [Select] photos.php?album={$id} No matter what album you're in (be it the "father" parent album or a nested album) Now, what I want to do is construct a method to add to my "photos" class, that creates an array of all parent album id's depending on the current nested album, so I can use that array to display a "navigation" type thingy-ma-jigger at the top of each page. For example: Current album is "Ghosts" Navigation would look like: Paranormal Activity -> Experiences -> Ghosts Where "Ghosts" and "Experiences" are albums nested in "Paranormal Activity" I figure you'd have to go about this using a loop of some kind, but I can't for the life of me figure it out. The only thing I can think of to do that doesn't entirely solve this problem is get the parent id of the current album. So as of right now, if "Ghosts" is currently being displayed, I can output a link taking you to "Experiences", but I can't do so to get "Paranormal Activity". I mean I could, but I'd have to loop through twice to get both ID's. I need a method that will loop through infinitely until there are no more parent albums to be found. Hope this all makes sense. Here's my code for viewing an album, just so you can get a clear picture (I'm using the Smarty extension case the HTML code confuses you) Code: [Select] <div id='view_album'> <!--<a href='photos.php?album={$PARENT_ALBUM_ID}'>« Back to {$PARENT_ALBUM_NAME}</a>--> <div class='album_name'> {$ALBUM_NAME} </div> <div class='album_info'> Created by <a href=''>{$USERNAME}</a> (<a href="photos.php?album={$PARENT_ALBUM_ID}">{$PARENT_ALBUM_NAME}</a>) {$DATE_FANCY} • Updated {$LAST_DATE_FANCY} {if strlen($LOCATION) > 0} • Taken at {$LOCATION} {/if} {if $smarty.const.PHOTOS_ADMIN_ACCESS == true} • <a href='photos.php?album={$ALBUM_ID}&action=edit'>Edit Album</a> • <a href='photos.php?album={$ALBUM_ID}&action=delete'>Delete Album</a> • <a href='photos.php?album={$ALBUM_ID}&action=upload&max=1&submit=false'>Upload Photos</a> {/if} </div> <!--Start albums--> {$i= 0} {$max_columns = 5} {$column_width = 100 / {$max_columns}} <table width='100%'> {foreach $ALBUMS_ARRAY as $id => $id} {if $i == 0} <tr> {/if} <td width='20%' align='center'> <div class='album_graphic_container'><a href='photos.php?album={$id}'> {if {albums::info ("id", "=", {$id}, "cover")} == 0} <a href="photos.php?album={$id}"><img src='photos/images/icons/album_default.png'></a> {else} <img src='photos/covers/{$id}/default.jpg' style="width: 100%;"/> {/if} </div> <div class='album_graphic_info'> <a href='photos.php?album={$id}'>{albums::info ("id", "=", {$id}, "name")}</a> <br> {albums::info ("id", "=", {$id}, "num_albums")} Albums • {albums::info ("id", "=", {$id}, "num_photos")} Photos <br> <a href='' style='font-size: 100%;'>{albums::info ("id", "=", {$id}, "num_comments")} Comments</a> </div> </td> {$i = $i + 1} {if $i == $max_columns} </tr> {$i = 0} {/if} {/foreach} {if $i < $max_columns} {$j = 0} {for $k = $i; $k < $max_columns - 1; $k++} {if $j == 0} <td width='{$column_width}%' align='center'> <div class='album_graphic_container'> <a href='photos.php?album={$ALBUM_ID}&action=compose'> <img src='photos/images/icons/album_default.png'> </a> </div> <div class='album_graphic_info'> <a href='photos.php?album={$ALBUM_ID}&action=compose'>+ Add New Album</a> <br> <br> </div> </td> {/if} {$j = 1} <td width='{$column_width}%' align='center'> </td> {/for} {else} {/if} </table> <!--Start photos--> <div class='view_album_lft'> {if {albums::info ("id", "=", {$ALBUM_ID}, "num_photos")} == 0} {else} <!--<div class='view_album_photos_header'>"; Photos In <a href=''>" . albums::info ("id", "=", $_GET["album"], "name") . "</a> (" . albums::info ("id", "=", $_GET["album"], "num_photos") . ")"; </div>";--> {$p = 0} {$p_max_columns = 6} {$p_column_width = 100 / $p_max_columns} <table width='100%'> {foreach $PHOTOS_ARRAY as $id => $id} {if $p == 0} <tr> {/if} <td width='{$p_column_width}%' align='center'> <div class='album_graphic_container'> <a href='photos.php?album={$ALBUM_ID}&photo={$id}'><img src='{photos::info ("id", "=", $id, "src_thumb_medium")}' style='width: 100%;'></a> </div> <div class='album_graphic_info'> {photos::info ("id", "=", {$id}, "views")} Views <br> {photos::info ("id", "=", {$id}, "num_comments")} Comments </div> </td> {$p = $p + 1} {if $p == $p_max_columns} </tr> {$p = 0} {/if} {/foreach} {if $p < $p_max_columns} {for $q = $p; $q < $p_max_columns; $q++} <td width='{$p_column_width}%'> </td> {/for} {/if} </table> {/if} </div> <div class='album_info_2_lft'> {if {likes::determine ("album", {$ALBUM_ID}, $smarty.const.PHOTOS_USER_LOGGED)} == -1} {$NUM_LIKES} Likes • <a href="photos.php?album={$ALBUM_ID}&action=like">Like this album</a> | {$NUM_DISLIKES} Dislikes • <a href="photos.php?album={$ALBUM_ID}&action=dislike">Dislike this album</a> {/if} {if {likes::determine ("album", {$ALBUM_ID}, $smarty.const.PHOTOS_USER_LOGGED)} == 1} {$NUM_LIKES} Likes • <a href="photos.php?album={$ALBUM_ID}&action=unlike">Unlike this album</a> | {$NUM_DISLIKES} Dislikes • <a href="photos.php?album={$ALBUM_ID}&action=dislike">Dislike this album</a> {/if} {if {likes::determine ("album", {$ALBUM_ID}, $smarty.const.PHOTOS_USER_LOGGED)} == 0} {$NUM_LIKES} Likes • <a href="photos.php?album={$ALBUM_ID}&action=like">Like this album</a> | {$NUM_DISLIKES} Dislikes • <a href="photos.php?album={$ALBUM_ID}&action=undislike">Undislike this album</a> {/if} </div> <div class='album_info_2_rt'> {$DOWNLOADS} Downloads • <a href="photos.php?album={$ALBUM_ID}&action=download">Download this album</a> </div> <br clear="all" /> <!--<div class='view_album_rt'> <div class='view_album_rt_header'> Share This Album </div> <div class='view_album_rt_header'> Download This Album </div> <a href=''>Low Quality ({albums::info ("id", "=", {$ALBUM_ID}, "album_size_low")})</a> <br> <a href=''>Medium Quality ({albums::info ("id", "=", {$ALBUM_ID}, "album_size_medium")})</a> <br> <a href=''>High Quality ({albums::info ("id", "=", {$ALBUM_ID}, "album_size_high")})</a> <br> <a href=''>Full Size Quality ({albums::info ("id", "=", {$ALBUM_ID}, "album_size_full")})</a> </div> <br clear='all'>--> <div class='view_album_comments_container'> <div class='view_album_comments_header'> All Comments ({$ALBUM_NUM_COMMENTS}) </div> <div class='view_album_comments_add'> {if !{$PHOTOS_USER_LOGGED}} You must <a href='login.php'>login</a> or <a href='register.php'>sign up</a> in order to post comments {else} {if $COMMENTS_DISABLED == 0} <div class='view_album_comments_single_wrapper'> <div class='view_album_comments_single_lft'> <img src='members/{users::info ($smarty.const.PHOTOS_MEMBERS_FIELD_ID, "=", $smarty.const.PHOTOS_USER_ID, "avatar_src")}'> </div> <div class='view_album_comments_single_rt'> <form action='photos.php?album={$ALBUM_ID}&comment=new&action=add' method='post'> <input type='hidden' name='parent_id' value='0' /> <textarea name='body' placeholder="Write your response" class='view_album_comments_add_textarea'></textarea> <span style="float: right;"><input type="submit" class="fb_button_blue" value="Post Comment" /></span> </form> </div> <br clear='all'> </div> {else} Comments for <a href=''>{$ALBUM_NAME}</a> has been disabled {/if} {/if} </div> {foreach $COMMENTS_ARRAY as $id => $id} <div class='view_album_comments_single_wrapper'> <div class='view_album_comments_single_lft'> <img src='members/{users::info ($smarty.const.PHOTOS_MEMBERS_FIELD_ID, "=", {comments::info ("id", "=", {$id}, "user_id")}, "avatar_src")}'> </div> <div class='view_album_comments_single_rt'> <div class='view_album_comments_single_rt_username'><a href=''>{comments::info ("id", "=", {$id}, "username")}</a></div> <div class='view_album_comments_single_rt_body'>{comments::info ("id", "=", {$id}, "body")}</div> <div class='view_album_comments_single_rt_info'> {comments::info ("id", "=", {$id}, "date_fancy")} • <a href="">Like</a> | <a href="">Dislike</a> {if $smarty.const.PHOTOS_USER_LOGGED == true} {if $smarty.const.PHOTOS_ADMIN_ACCESS || $smarty.const.PHOTOS_USER_ID == {comments::info ("id", "=", {$id}, "user_id")}} • <a href="">Delete</a> {/if} • <a href="">Report</a> {/if} </div> </div> <br clear="all" /> </div> {/foreach} <div id='view_album_comment_report'> <div id='view_album_comment_report_body'> <span class='view_album_comment_report_body_header'>Report Comment</span> </div> </div> </div> </div> Need more info, just ask. Thanks. I am using a foreach loop to get the results of an array. My problem is that I need the results combined into one string. How can I accomplish this? Currently I have 5 entries in my table. Entring this query displays all five in the correct order. Code: [Select] SELECT * FROM products ORDER BY count DESC LIMIT 16 However, using this code, the first result is omitted and the last four are displayed. $query="SELECT * FROM products ORDER BY count DESC LIMIT 16"; $result = mysql_query($query); $row = mysql_fetch_array($result); echo '<div>'; while ($row = mysql_fetch_array($result)) { echo '<div>'.$row[product].'</div> <div>'.$row[count].'</div>'; } echo '</div>'; Can someone help me find my error? Thanks I'm trying to take a number of items from a database using a while loop and put the results into a variable so that I can send one email with all the results. I'm having trouble figuring this out though. Can anyone please give me any ideas as to how to make this work? Here's what I've done so far... all it does is result in an email with the first set of results in the while loop, not all of them. Code: [Select] <?php include("conf.inc.php"); $result = mysql_query("SELECT `to`,`from`,`subject`,`message`,`date` FROM allmsgs WHERE reported = 'n' ORDER BY `messid` ASC"); $row = mysql_fetch_row($result); $cdate = date('m-d-Y'); $sendto = "List@emails.here"; $emailsubject = "Webstats Report For $cdate."; while ($row = mysql_fetch_row($result)) { $to = $row[0]; $from = $row[1]; $subject = $row[2]; $message = $row[3]; $datetime = $row[4]; $eachmessage = "<p> <table width=\"400\"> <tr> <td> <hr width=\"400\"> To: $to<br> From: $from<br> On $datetime<br> <br> $subject<br> <br> $message </td> </tr> </table> </p>"; } $emailmessage = "<html> <body> <p>Here is a list of the messages that have been exchanged in the last 24 hours using the webstat system system.</p> $eachmessage </body> </html>"; // To send HTML mail, the Content-type header must be set $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Additional headers $headers .= 'From: Webstats <reports@webstats.com>' . "\r\n"; // Mail it mail($sendto, $emailsubject, $emailmessage, $headers); ?> So I have 2 queries, that has the potential to return alot of data, foreach loops running. The first shows each group heading, and the foreach nested is calling another query specific to the group heading. The result currently is a lengthy delay in results showing. (Now this may/may not be the most ideal code practise in this instance however... short term solution discussion please). For Each State Read Each States Details from DB For Each State Listing Display Details Next Next Is there a command or other where I can say, Display HTML page as it stands while it continues to process the FOREACH loops? EG: For Each State Read Each States Details from DB For Each State Listing Display Details REFRESH HTML DISPLAYED Next Next Hey guys, I'm building an E-commerce store for a T-Shirt selling company, I've assembled the shopping cart etc correctly but I am having problems within building a forum based system for the site admin to post Bulletins and Notices to the homepage + a blogging page. I am using a while loop which should iterate the results at the end of each cycle through my variable $postResult Here is my code... <?php include_once "../scripts/db_connect.php"; // Connect to the database // Get the section ID from the url variable coming in $sqlout = mysql_query("SELECT * FROM blog_posts ORDER BY ordered ASC LIMIT 10"); if (isset($_GET['id']) && $_GET['id'] != "") { $sid = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter all characters except numbers for security } else { echo "ERROR: Variables to run this script have been removed from the URL."; exit(); } // Query the database for that section id, make sure it exists and get the section title $sql = mysql_query("SELECT * FROM blog_category WHERE forum_id='$sid' LIMIT 1"); $numRows = mysql_num_rows($sql); if ($numRows < 1) { echo "ERROR: That section deos not exist you have tampered with our URLs."; exit(); } while($row = mysql_fetch_array($sql)){ $sectionTitle = $row["forum_title"]; } // Use the section ID to query the "forum_posts" table in the database to get all the threads for this section $sql = mysql_query("SELECT * FROM blog_posts WHERE type='a' AND section_id='$sid' ORDER BY date_time DESC LIMIT 10"); $postResult = ''; $numRows = mysql_num_rows($sql); if ($numRows < 1) { $postResult = "There are no threads in this section yet. You can be the first to post."; } else { while($row = mysql_fetch_array($sql)){ $thread_id = $row["id"]; $post_author = $row["post_author"]; $post_author_id = $row["post_author_id"]; $date_time = $row["date_time"]; $convertedTime = ($myAgoObject -> convert_datetime($date_time)); $whenPost = ($myAgoObject -> makeAgo($convertedTime)); $thread_title = $row["thread_title"]; $dynamicList .= '<img src="style/threadPic.jpg" width="26" height="18" alt="Topic" /> ' . $post_author . ' - <a href="view_thread.php?id=' . $thread_id . '">' . $thread_title . '</a> - ' . $whenPost . '<br />'; } } ?> And here is a snippet of where I echo the results in my HTML: <br /><br /> <div style="margin-left:12px; "><?php echo $postResult; ?></div> <br /><br /><br /></td> I have been slaving over this for hours now, the first $postResult variable will always iterate its text of "There are no threads in this section yet. You can be the first to post.", I can't see anything wrong in my SQL syntax as I have a similar set up to iterate my products to different pages and that has always worked fine Any input on this would be great Kind Regards Alex. what I need is for a loop to run to make tabbed pannels according to categories. then I need the buttons to be put into the correct tab based on the category it falls under. then a subcategory tabs inside the other tabs for products that have that specific sub category. here is what I sorta made....it doesn't work though.... Code: [Select] <div id="TabbedPanels1" class="TabbedPanels"> <ul class="TabbedPanelsTabGroup"><?php $sql = mysql_query("SELECT * FROM categories"); while($row = mysql_fetch_array($sql)){ $category = $row["category"]; $sub =$row["subcategory"]; ?> <li class="TabbedPanelsTab" tabindex="0"><?php echo $category; ?></li> <div class="TabbedPanelsContentGroup"> <div class="TabbedPanelsContent"> <?php // set layout vars $x = 1; // set $x $start = array ('1', '10', '19', '28', '37', '46', '55', '64', '73', '82', '91', '100', '109', '118', '127', '135'); //columns will be started at each of these numbers $end = array( '9', '18', '27', '36', '45', '54', '63', '72', '81', '90', '99','108','117', '126' ); // set numbers to end columns at ?> <?php echo '<table border="1px" cellpadding="0px" cellspacing="0px" ><tr height=\'50px\'>'; //start the table, and the row. // Query member data from the database and ready it for display $sql = mysql_query("SELECT * FROM products where category=".$category.""); while($row = mysql_fetch_array($sql)){ $product = $row["product"]; $id =$row["id"]; $price =$row["price"]; if (in_array($x, $start)) { // if x equals a number in the start array echo '<td width="100">'; // start a column } ?> <?php $sql = mysql_query("SELECT * FROM categories"); while($row = mysql_fetch_array($sql)){ $category = $row["category"]; $sub =$row["subcategory"]; ?> <?php } ?> <div id="products"> <form action="" method="POST" name="myform<?php echo $id; ?>" class="myform<?php echo $id; ?>"> <input type="hidden" name="hiddenField" class="hiddenField" value="<?php echo $product; ?>" /> <input type="hidden" name="hiddenField2" class="hiddenField2" value="<?php echo $id; ?>" /> <input type="hidden" name="hiddenField1" class="hiddenField1" value="<?php echo $price; ?>" /> <input type="submit" name="submit" class="submit" value="<?php echo $product; ?>" style="background-color:lightgreen; height:50px; padding: 0px; margin:0px; width:100px;"> </form> </div> <?php if (!in_array($x, $end)){ // if $x equals anything OTHER than 9, 18, etc - put in a line break } else { // else if it DOES equal 9, 18 ,etc end the column echo '</td>'; } $x ++; // increase x to keep count } // while loop ends //now outside of the loop, $x = $x - 1; //subtract the last $X++ so you know exactly how many buttons were added if (!in_array($x, $end)){ // if $x equals anything OTHER than 9, 18, etc - end the column as it wouldn't have ended itself echo '</td>'; } echo '</tr></table>'; // close the row and table ?><?php } ?> </div> </ul> </div> any help is greatly appreciated. How can I make this output in descending order from greatest to least? Right now, it appears like: 1940 1941 1942 1943 1944 etc... i'd like it to be like 2012 2011 2010 2009 etc.. until it gets to 1940 any ideas? here is my code: <? $i = 1939; while ($i < 2012) { $i++; echo '<option value="'.$i.'">'.$i.'</option>'; } ?> |