PHP - For Loop & While Loop Working, But Results Are Wrong In Both
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 Similar TutorialsThe first WHILE loop in the code below is executing correctly on the first go-round, and successfully updating the trade_offers table at the end of the loop. In the 2nd go round, it should use the updated values from trade_offers, but instead is using the original values. Would appreciate any help in locating the problem. There are no errors being output. Code: [Select] $getdeclined="SELECT * FROM trade_offers WHERE pokemon_trade_id=$id"; $declined=mysql_query($getdeclined); while($row = mysql_fetch_array($declined)){ $getpostrade="SELECT * FROM trade_offers WHERE pokemon_trainer = '$row[pokemon_trainer]'"; $postrade=mysql_query($getpostrade) or die(mysql_error());; while ($row2 = mysql_fetch_array($postrade)){ $tradepos = $row2['pokemon_pos'];} if ($tradepos==NULL){ $tradepos=0;} $getpostrainer="SELECT * FROM pokemon_trainer WHERE pokemon_trainer = '$row[pokemon_trainer]'"; $postrainer=mysql_query($getpostrainer) or die(mysql_error());; while ($row3 = mysql_fetch_array($postrainer)){ $trainerpos = $row3['pokemon_pos'];} if ($tradepos>$trainerpos){ $newpos = $tradepos;} else if ($trainerpos>$tradepos){ $newpos = $trainerpos;} $newpos +=1; $update="UPDATE trade_offers SET pokemon_pos = $newpos WHERE pokemon_id = $row[pokemon_id]"; $result=mysql_query($update) or die(mysql_error());; $newpos = 0; } 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 hi all, I have possibly up to 9 images that I want to find and show on a webpage. I am trying to put a $file in a loop and get all the .jpg images that are found in to an array and show them all. I think from the script you can see what I am attempting to do! Any pointers would be grateful for <?php while($i=0 $i < 9 $i++) { $file = "aircraft/".$_GET['reg'].$i.".jpg"; } foreach($file) { echo "<li class=\"active\"><img src=\"./aircraft/".$reg.$i.".jpg\" alt=\"Flowing Rock\" style=\"width: auto; height: 70px; margin-left: -28.5px; display: block;\" class=\"thumb\" ><br />"; } ?> 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? 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? 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. 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! I have a loop that writes out data for franchises. It works the first time through, but not the 2nd. Here is the page where the data is written out: http://184.172.137.97/~royl21st/1.php Here is the code that spits out the wrong data after the first successful loop. Any ideas? Code: [Select] $areaCodeData = getData($sSql, $con, $dbName); $areaCodeRowCount = mySQL_num_rows($areaCodeData); $areaCodeRowCur = mysql_fetch_assoc($areaCodeData); if ($areaCodeRowCount != 0) { echo "<div class='box left'>"; // list all Area Codes for this Franchise echo "<div class='details'>"; $areaCodes = ""; for ( $ctrAreaCode = 0; $ctrAreaCode <= $areaCodeRowCount - 1; $ctrAreaCode += 1) { // grab AreaCodes $areaCodes = "<b>".$areaCodes.$areaCodeRowCur['AreaCode']."</b>, "; // fetch next AreaCode row $areaCodeRowCur = mysql_fetch_assoc($areaCodeData); } // end ctrAreaCode for loop $areaCodes = substr($areaCodes, 0, strlen($areaCodes)-2)."<br />"; echo "<em>-- Area Codes Supported:</em><br/>"; echo $areaCodes; echo "</div>"; echo "</div><br />"; } //end Area Code loop // reset AreaCode loop pointers (is this a PHP bug?) mysql_data_seek($areaCodeData,0); At this point I'm desperate and I have to get this working ASAP. The Grand Rapids, Kalamazoo, Holland area codes are 616, 269, 616 and their area codes are 49xxx Thanks in advance for the help... 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 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. 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. 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.
So the issue I'm having is consecutive loops on semi-large arrays, over and over. Consider this array:
$firstArray = array( 'row1' => array( 'dates' => array( '2014-01-01' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-02' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-03' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-04' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-05' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-06' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-01-07' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), ) ), 'row2' => array( 'dates' => array( '2014-02-01' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-02' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-03' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-04' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-05' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-06' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-07' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-08' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), '2014-02-09' => array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'key4' => 'value4', 'key5' => 'value5', 'key6' => 'value6', 'key7' => 'value7', 'key8' => 'value8', 'key9' => 'value9', 'key10' => 'value10'), ) ) );Originally the data comes from ~2-3 database tables, of course. But to ilustrate the point, this is how the main array looks like. This array usually contains anywhere between 10-50 rows, each row containing at least 10 dates, with 10 key/values each. And after setting up all the data, it needs to be processed. Currently this is how a friend of mine did it.. $placeDataHere = array(); foreach($firstArray as $key => $dates) { foreach($dates as $date => $values) { foreach($values as $key => $value) { $placeDataHere['DV_' . $date]['SM_' . $key] = 'KS_' . $value; //Followed by another ~50-70 lines of processing the 3 loop's data.. ... ... .... .... .... .... .... .... } } }Obviously this isn't good practise, but we can't seem to figure out a better way of doing it, since both the data and the loops are horribly nested. This loop and setup of $firstArray is run anywhere between 10-20 times/request, due to amount of users we wish to process. So, the result is that this code can take up to over 2-3 minutes to complete, which isn't really optimal performance. In short my question is, are there any better methods of handling this with the data setup we currently have? Hello, Having a bit of a tough time understanding what is going on in my brain! I'm basically pulling some data from an API using CuRL, which is working fine. The structure of the data is: [data][tickets] - tickets being an array of support tickets in the system, which then contains ticketNumber, title, content. I want to display these values in a list, I have this code currently: if ($err) { echo "cURL Error #:" . $err; } else { $return = json_decode($response, true); foreach($return as $key) { echo $key["tickets"][1]['ticketNumber']." - "; echo $key["tickets"][1]['title']." - "; echo $key["tickets"][1]['content']; } } Which obviously returns the ticketNumber, title & content of the first support ticket in the array, but I want to loop through and display that information for each ticket! Can anyone advise as to where I am going wrong? I think I need to utilise the ["tickets"][x] but not sure how!
Thanks in advance! Steve 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>'; } ?> What im trying to achieve is a user contact system, when the user types input in the textarea its saved in a database along with his userid on the site and the date, I have an admin side coded up where it retrieves the data, but there is no order. I want to have it display the most recent results on top. I have looked into this in the mysql manual, but you know how that is its so hard to make sense of anything in that damn manual. Im using a while loop to display the data. How can I achieve this? I have a search form that has a drop down Code: [Select] <select name="radius" id="radius"> <option value="5">5 mi.</option> <option value="10">10 mi.</option> <option value="15">15 mi.</option> <option value="20">20 mi.</option> <option value="50">50 mi.</option> <option value="100">100 mi.</option> </select> I'm trying to limit the results in a foreach loop within what was selected. Meaning, if someone selects 10, results within 10 miles will show The foreach is Code: [Select] foreach ($stores as $k=>$v) { $output = "<h3 style='margin:0;padding:0'><b>".$storeinfo[$k]['MktName']."</b><br>(approx ".$v." miles)</h3>"; $output .= "<p style='margin:0 0 10px 0;padding:0'>".$storeinfo[$k]['LocAddSt']."<br>"; $output .= $storeinfo[$k]['LocAddCity'].", ".$storeinfo[$k]['LocAddState']." ".$storeinfo[$k]['zipcode']."</p>"; print_r($output); } $v being the distance. So I need to show only the results of $v that are less than $r. How would I go about doing this? Right now, $v displays numbers like 5.04, 173.9 and so forth. Can anybody help me out? Thanks in advance. Hello, i have the code below and i need to have all results in a variable as a string, inside the loop they are displayed how i want but outside will echo the last result. Thank You. Code: [Select] foreach($_POST as $key=>$value){ if (is_numeric($value)) { $valoare = "$value,"; } } echo $valoare; This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=333337.0 |