Loops in PHP
Topics
Is there any way to invert a Do-While loop so it continues to loop through the Do statement if the While statement is FALSE. And then end execution once the While statement is true. Code: [Select] do{ $length = 2; $characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $string =""; $string.= microtime(true); for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } $string= substr_replace($string, '', 0, 4); for ($p = 0; $p < $length; $p++) { $string2 .= $characters[mt_rand(0, strlen($characters))]; } $string="".$string2."".$string; $string=explode(".",$string); $string=$string[0].$string[1]; $rma_number=$string; $sql12345="SELECT * FROM $tbl_name4 WHERE rma_number=$rma_number"; $result12345=mysql_query($sql12345); $num_rows12345=mysql_num_rows($result12345); } while($num_rows12345 < 1){ $sql2000000="UPDATE $tbl_name4 SET rma_number='$rma_number', rma_name='$rma_name' WHERE rma_id = $rma_id"; mysql_query($sql2000000); } I am not getting any error messages as I just think the codes are wrong. I am trying to get the $sql(s) to choose and print out the the looking_for in the database. However it is not printing anything. Any ideas of where I am need to fix this. I have tried a few ways with no luck. $sql = mysql_query("SELECT id,gender,looking_for FROM Members"); $nr = mysql_num_rows($sql); $sql2 = mysql_query("SELECT * FROM Members WHERE id='".($_POST['$looking_for'])."' LIMIT $pn, $itemsPerPage"); $outputList = ''; while($row = mysql_fetch_array($sql2)) { $id = $row["id"]; $username = $row["username"]; $firstname = $row["firstname"]; if (!$firstname) { $firstname = $username; } $gender=''; $looking_for=''; For some reason I'm getting an invalid argument supplied for foreach error and I'm not sure why. Code: [Select] <?php // Include the database page require ('../inc/dbconfig.php'); if (isset($_POST['edit_event_lineup'])) { $event_items = $_POST['event_items']; $event_id = (int)$_POST['event_id']; foreach ($event_items as $items) { print_r($items); $segment_writer_id = (int)$_POST['segment_writer_id']; $introduction = mysqli_real_escape_string($dbc, $_POST['introduction']); $conclusion = mysqli_real_escape_string($dbc, $_POST['conclusion']); $segment_type = mysqli_real_escape_string($dbc, $_POST['segment_type']); $match_number = (int)$_POST['match_number']; $segment_number = (int)$_POST['segment_number']; $match_type_id = (int)$_POST['match_type_id']; $segment_title = mysqli_real_escape_string($dbc, $_POST['segment_title']); $match_type_id = mysqli_real_escape_string($dbc, $_POST['match_type_id']); $titles_id_list = mysqli_real_escape_string($dbc, $_POST['titles_id_list']); $stipulations_id_list = mysqli_real_escape_string($dbc, $_POST['stipulations_id_list']); $characters_id_list = mysqli_real_escape_string($dbc, $_POST['character_id_list']); $preview = mysqli_real_escape_string($dbc, $_POST['preview']); } $query = "INSERT INTO `event_segments` (event_id, segment_writer_id, segment_type, sort_order_preview, segment_title, preview, is_submitted_yes_or_no_id) VALUES ('".$event_id."', '".$match_writer_id."', '".$segment_type."' ,'".$sort_order_preview."','".$segment_title."','".$preview."',2)"; mysqli_query($dbc, $query); } ?> 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? My while loop to do the process to every member_id won't work.Its only printing one member_id thats done.Also my INSERT statement wont insert even that 1 member_id. Can someone please point my mistake. Code: [Select] <?php include 'config.php'; function tree_gather($node) { $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'"; $execsql = mysql_query($sql); $array = mysql_fetch_array($execsql); if(!empty($array['lchild']) || !empty($array['rchild'])) { if(!empty($array['lchild'])) $child[] = $array['lchild']; if(!empty($array['rchild'])) $child[] = $array['rchild']; if(!empty($array['lchild'])) $lchild = tree_gather($array['lchild']); if(!empty($array['rchild'])) $rchild = tree_gather($array['rchild']); if(!empty($lchild) && !empty($rchild)) { $merge_both = array_merge($lchild, $rchild); $child = array_merge($child, $merge_both); } elseif(!empty($lchild) && empty($rchild)) $child = array_merge($child, $lchild); elseif(!empty($rchild) && empty($lchild)) $child = array_merge($child, $rchild); } return $child; } $sql = mysql_query("SELECT member_id FROM member"); while($array = mysql_fetch_array($sql)) { $memid = $array['member_id']; $pair = tree_gather($memid) ; $remove = mysql_query("SELECT lchild,rchild FROM tree WHERE parent ='".$memid."'"); $remove_array = mysql_fetch_array($remove); if(!empty($remove_array['lchild']) || !empty($remove_array['rchild'])) { $count = count($pair); for($i = 0 ; $i < $count ; $i++) { if($pair[$i] != $remove_array['lchild'] && $pair[$i] !=$remove_array['rchild']) { $trimmed[] = $pair[$i]; } else { $two_one[] = $pair[$i]; } } } $add = mysql_query("SELECT lchild,rchild FROM tree WHERE parent='".$remove_array['lchild']."'"); $add_array = mysql_fetch_array($add); if(!empty($add_array['lchild']) || !empty($add_array['rchild'])) { $count = count($trimmed); for($i=0;$i < $count ; $i++) { if(!empty($add_array['lchild'])) { if($add_array['lchild'] == $trimmed[$i]) { $two_one[] = $add_array['lchild']; unset($trimmed[$i]); $done = 1; break; } } if(!empty($add_array['rchild']) && $done !=1) { if($add_array['rchild'] == $trimmed[$i]) { $two_one[] = $trimmed[i]; unset($trimmed[$i]); $done = 1; break; } } } } if($done != 1) { $add = mysql_query("SELECT lchild,rchild FROM tree WHERE parent='".$remove_array['rchild']."'"); $add_array = mysql_fetch_array($add); if(!empty($add_array['lchild']) || !empty($add_array['rchild'])) { $count = count($trimmed); for($i=0;$i < $count ; $i++) { if(!empty($add_array['lchild'])) { if($add_array['lchild'] == $trimmed[$i]) { $two_one[] = $add_array['lchild']; unset($trimmed[$i]); $done = 1; break; } } if(!empty($add_array['rchild']) && $done !=1) { if($add_array['rchild'] == $trimmed[$i]) { $two_one[] = $trimmed[i]; unset($trimmed[$i]); $done = 1; break; } } } } } $select_child = mysql_query("SELECT rchild,lchild FROM tree WHERE parent='".$memid."'"); $select_array = mysql_fetch_array($select_child); if(!empty($select_array['rchild'])) $rchild = tree_gather($select_array['rchild']); $rchild[] = $select_array['rchild']; if(!empty($select_array['lchild'])) $lchild = tree_gather($select_array['lchild']); $lchild[] = $select_array['lchild']; if(!empty($rchild)) { $right_count = count($rchild); } if(!empty($lchild)) { $left_count = count($lchild); } if($right_count < $left_count) { $pair_num = $right_count; } elseif($right_count == $left_count) { $pair_num = $right_count - 1; } else { $pair_num = $left_count; } if(count($two_one) == 3) { $dues_adjust = 100; if($pair_num >= 1) { $dues_adjust = $dues + 100; $calcom = 200 * $pair_num; $tds = 20.60 * $pair_num; $service = 9.40 * $pair_num; $paid = $calcom - $dues_adjust; $insert = mysql_query("INSERT INTO `payout` (member_id, binary, tds, service, total, dues, amount_paid, dues_adjust, pairs) VALUES ('".$memid."', '".$calcom."', '".$tds."', '".$service."', '".$calcom."', '0', '".$paid."', '".$dues_adjust."', '".$pair_num."')"); unset($pair); echo "<br />".$memid." Done"; } } } ?> i have an array in the loop but it isn't building up with results. i want it to check if the array exists, if not then create the array. Then in next loop it pushes a new value into the array. Below isn't working?... Code: [Select] while($row=mysql_fetch_assoc($get)); { $key = $row['keyword']; $scope= $_SESSION['scope']; if (!is_array($scope)) { $scopenew = array($key); $_SESSION['scope'] = $scopenew; } else { $scopenew = array_push($scope, $key); $_SESSION['scope'] = $scopenew; } } Code: [Select] <?php $HitlistHeader = file_get_contents(url); $Hitlist = simplexml_load_string($HitlistHeader); foreach($Hitlist->xml->entry as $entry) { foreach($entry->target_user as $target) { $TargetID=$target->user_id; $TargetName=urldecode($target->mob_name); } foreach($entry->paid_user as $paiduser) { $PaidID=$paiduser->user_id; $PaidName=urldecode($paiduser->mob_name); } $Amount=$entry->amount; $TimeAgo=$entry->placed_time_ago; $Level=$entry->level; } for($cwb=1; $cwb!=count($entry); $cwb++) { echo $TargetID[$cwb]."\n"; echo $TargetName[$cwb]."\n"; echo $PaidID[$cwb]."\n"; echo $PaidName[$cwb]."\n"; echo $Amount[$cwb]."\n"; echo $TimeAgo[$cwb]."\n"; echo $Level[$cwb]."\n\n"; } sleep(100000); ?> it only echoes one character on only a few of the variables, I dont know what the problem could be.. Anyhelp to resolve this is appreciated This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=333337.0 Hello, What im trying to do is show under each category some pictures... I found this code and change it a little bit, but its still shows only one category and the images... Any suggestions how im gonna change it to show all my category's? Code: [Select] <div id="PastProjects">Past Projects</div> <?php $query = mysql_query("SELECT * FROM tbl_pastprojects"); $counter = 0;//Use this as a way to ID data as it comes in. while($row = mysql_fetch_assoc($query)) { $catid[$counter] = $row['IssueId']; $catname[$counter] = $row['Title']; $Counter++; } $NumTimes = count($catid); //Establishing a number of times to run the second loop for($i=0; $i<=$NumTimes; $i++) { $query1 = mysql_query("SELECT * FROM tbl_pastprojects_entries WHERE IssueId = ".$catid[$i].""); $c=0;//Another Counter for SubID's while($row = mysql_fetch_assoc($query1)) { $subid[$i][$c] = $row['Id']; $sname[$i][$c] = $row['Thumb']; $c++; } } //Now all of the Cats are stored in 2 Arrays(1 For name and 1 for ID) and SubCats are in 2 Multi Arrays(1 For name and 1 for ID) ///Generate Display for($j=0; $j<$NumTimes; $j++) { echo("<div id='PastProjectstitle'>"); echo($catname[$j]); echo("</div>"); //Establish Count for sub cats $NumCats = count($subid[$j]);//This counts the second dimension of the array (which is the num of sub categorys for that particular category) echo("<div id='PastProjectsImages'>"); //Loop through each SubCat for($k=0; $k<$NumCats; $k++) { echo("<img src='".$sname[$j][$k]."' />"); } echo("</div>"); } ?> Hello! I am going to end up ending with many If-Else statements so I'm hoping someone can change this into a for loop for me, I will learn this way too Code: [Select] if(empty($_GET['start'])) { $active_1_20 = 'active'; $limit_by = 'LIMIT 0,20'; $rank = 1; } elseif($_GET['start']==21) { $active_21_40 = 'active'; $limit_by = 'LIMIT 20,40'; $rank = 21; } elseif($_GET['start']==41) { $active_41_60 = 'active'; $limit_by = 'LIMIT 40,60'; $rank = 41; } elseif($_GET['start']==61) { $active_61_80 = 'active'; $limit_by = 'LIMIT 60,80'; $rank = 61; } You can see the obvious pattern, next one will be elseif($_GET['start']==81) and I want it to end to elseif($_GET['start']==501) Much appreciated anyone! Thanks. Ok, so first off, here is how the tables are setup: Cars_Table | ID, CatID Categories_Table | ID, Parent_ID, Name Now, both parent categories and sub-categories are in the same table. the C_Table.CatID shows only the sub-category the item is in. How would I make a list of the distinct names of Parent category names (those with Parent_ID = 0) in ASC order, but I want to only pull the parent categories for which there is an item associated. Essentially, the makes and models of the cars are stored in the same table, the Makes are the ones with Parent_ID = 0 and the Models also have parent ID's. The Cars_Table.CatID only shows the Model ID. I'm still fairly new to PHP and this one is really confusing me O.o Hi there, Having an issue here. I have a site where you can join a group. When the user goes to the groups page it will list their groups that they have joined. This is fine. I also want to be able to show how many other members are in that group and am getting stuck. $row group_name works ok but not sure how to start by adding another while loop in for the members. The table consists of group id, group name, member id (L_ID) and member name $result = mysql_query("SELECT * FROM groups2 WHERE L_ID = ". $_SESSION['member_ID'] .";"); while ( $row = mysql_fetch_array($result) ) { echo("<tr> <td><font face='Arial, Helvetica, sans-serif' size='3'><strong>" . $row["group_name"] . "</strong></font></td> </tr><tr> <td><font face='Arial, Helvetica, sans-serif' size='1' color='#0000FF'><strong>Members ("???")</strong></font></td> </tr><tr> <td><hr width=95%><br></td> </tr>"); } Hi! I have a code that don't do want I want that to do. <?php $chars = str_split('abc'); $char_len = count($chars); $length = 3; //loop for char_len^length $loop_length = pow($char_len, $length); for($i = 0; $i < $loop_length; $i++) { //convert $a to chars $string = ''; while($a != 0) { $string = $chars[$a % $char_len] . $string; $a = (int) ($a / $char_len); } //pad and print string echo str_pad($string, $length, $chars[0], STR_PAD_LEFT), "<br>\n"; if($loop_length-1 == $i){ $length++; } } ?> And what it do, is to print out all combination of a, b and c. My problem is that when the loop is done (you'll se my if statement) I want to add one on length so it print out a, b and c in four letters. ex abca, abcb. But it isen't working. Have you any clue that can help me? Thank you for your answer. 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; Now I am stumped this is far any help would be awesome This is what I have gotten so far, this is what it does right now is display each Header above each bit of data and spans across 5 columns for each foreach loop but what i am trying to understand here is i am trying to get the header then the data then another header and data and so on but only about 4 or number of my choosing grouped header/data but select how many are in each column up to 5 columns. Heres an example of what i am trying to do. A D K N S AlexandraHeadlands DickyBeach KingsBeach Nambour SandstonePoint Aroona Diddillibah KielMountain Ninderry ShellyBeach Doonan KundaPark NoosaHeads SippyDowns B Dulong Kuluin Ningi SunriseBeach Beachmere DeceptionBay Kilcoy NorthArm SunshineBeach BanksiaBeach Noosaville Scarborough Beerburrum E L Beerwah EerwahVale Landsborough O T Bellara Elimbah Tanawha Bellmere Eudlo M P TowenMountain Birtinya Eumundi Maleny Petrie Tewantin Bongaree Mapleton Palmview TwinWaters Bokarina F Marcoola Palmwoods BribieIslandArea Flaxton MarcusBeach Parklands U Buddina ForestGlen MaroochyRiver Parrearra UpperCaboolture Burnside Maroochydore PeregianBeach Buderim G Minyama Pinbarren V Burpengary GlassHouseMountains MoffatBeach PointArkwright Valdora BliBli Mons PelicanWaters H Montville PacificParadise W C Highworth Mooloolaba WeybaDowns CoolumBeach Hunchy Mooloolah Q Warana Caboolture MountainCreek WestWoombye CabooltureSouth I MountCoolum R Woombye Caloundra ImageFlat Morayfield Rosemount Woorim CastawaysBeach Mudjimba Redcliffe WamuranBasin Chevallum J Woodford CoesCreek WoodyPoint Cooroy Wamuran Currimundi Wurtulla X Y YandinaCreek Yandina Z This is an example of how it is being displayed right now A Airlie Beach Andergrove Alexandra Armstrong Beach Alligator Creek B Bucasia Blacks Beach Beaconsfield Bakers Creek Balberra Bloomsbury Breadalbane Ball Bay Belmunda C Cannonvale Calen Crystal Brook Cremorne Chelona Campwin Beach Cape Hillsborough Conway Heres The Code i have so far. Code: [Select] <?php $file = "widget.csv"; @$fp = fopen($file, "r") or die("Could not open file for reading"); $outputArray = array(); $count = 0; while(($shop = fgetcsv($fp, 1000, ",")) !== FALSE) { $outputArray[array_shift($shop)] = array_filter($shop); } echo "<table>"; foreach ($outputArray as $alphabetical=>$value){ echo "<th colspan='4'><b>" . $alphabetical ."</b></th>"; echo "<tr>"; foreach ($value as $key){ $afterkey=preg_replace('/\s+/','-',$key); if ($count == 4){ echo '</tr><tr><td><a href="map.php?mapaddress='.$afterkey.'-qld&mapname='.$key.'">'.$key.'</a></td>'; $count = 0; }else{ echo '<td><a href="map.php?mapaddress='.$afterkey.'-qld&mapname='.$key.'">'.$key.'</a></td>'; } $count++; } echo "</tr>"; $count = 0; } echo "</table>"; echo "\n<br />"; ?> Heres my CSV File: Quote A,Airlie Beach,Andergrove,Alexandra,Armstrong Beach,Alligator Creek,,,,,,,,,,,,,, B,Bucasia,Blacks Beach,Beaconsfield,Bakers Creek,Balberra,Bloomsbury,Breadalbane,Ball Bay,Belmunda,,,,,,,,,, C,Cannonvale,Calen,Crystal Brook,Cremorne,Chelona,Campwin Beach,Cape Hillsborough,Conway,,,,,,,,,,, D,Dows Creek,Dumbleton,Dolphin Heads,,,,,,,,,,,,,,,, E,Eimeo,Eton,Erakala,,,,,,,,,,,,,,,, F,Foulden,Foxdale,Flametree,Farleigh,Freshwater Point,,,,,,,,,,,,,, G,Glen Isla,Glenella,,,,,,,,,,,,,,,,, H,Homebush,Hampden,,,,,,,,,,,,,,,,, I,,,,,,,,,,,,,,,,,,, J,Jubilee Pocket,,,,,,,,,,,,,,,,,, K,Kinchant Dam,Kolijo,Koumala,Kuttabul,,,,,,,,,,,,,,, L,Laguna Quays,,,,,,,,,,,,,,,,,, M,McEwens Beach,Mackay,Mackay Harbour,Mandalay,Marian,Mia Mia,Middlemount,Midge Point,Mirani,Moranbah,Mount Charlton,Mount Jukes,Mount Julian,Mount Marlow,Mount Martin,Mount Ossa,Mount Pelion,Mount Pleasant,Mount Rooper N,Narpi,Nebo,Nindaroo,North Eton,,,,,,,,,,,,,,, O,Oakenden,Ooralea,,,,,,,,,,,,,,,,, P,Palmyra,Paget,Pindi Pindi,Pinevale,Pioneer Valley,Pleystowe,Preston,Proserpine,,,,,,,,,,, Q,,,,,,,,,,,,,,,,,,, R,Racecourse,Richmond,Riordanvale,Rosella,Rural View,,,,,,,,,,,,,, S,St Helens Beach,Sandiford,Sarina,Seaforth,Slade Point,Shoal Point,Shute Harbour,Shutehaven,Strathdickie,Sugarloaf,Sunnyside,,,,,,,, T,Te Kowai,The Leap,,,,,,,,,,,,,,,,, U,,,,,,,,,,,,,,,,,,, V,Victoria Plains,,,,,,,,,,,,,,,,,, W,Wagoora,Walkerston,Woodwark,,,,,,,,,,,,,,,, X,,,,,,,,,,,,,,,,,,, Y,Yalboroo,,,,,,,,,,,,,,,,,, Z,,,,,,,,,,,,,,,,,,, It's only displaying the first result and not the others. What am I doing wrong? I'm selecting the items the user occupies. Then I'm selecting the name and image of that item from the item table. Code: [Select] echo "<table cellspacing=\"0\" class=\"news\" align=\"center\">"; echo "<tr>"; $sql = "SELECT * FROM useritems WHERE userid='".$_SESSION['userid']."' LIMIT $offset, $rowsperpage"; //selects all the users items to whoever is logged in $result = mysqli_query($cxn,$sql) or die(mysqli_erro($cxn)); $imagecount = 0; while ($row = mysqli_fetch_assoc($result)) //while there are still results { extract($row); $quantity = $row['quantity']; $itemid = $row['itemid']; $sql = "SELECT * FROM items WHERE itemid='".$itemid."'"; //selecting the name and image of the item that is displaying $result = mysqli_query($cxn, $sql) or die(mysqli_error($cxn)); $row = mysqli_fetch_assoc($result); $name = $row['name']; $image = $row['image']; if ($imagecount%5 == 0) //after 5 items have been listed, start a new line { echo "</tr>"; echo "<tr>"; } } echo "<td width=\"120px\" align=\"center\">"; echo "<img src=\"http://www.elvonica.com/".$image."\"><br>"; echo $name." (".$quantity.")"; echo "</td>"; $imagecount++; //after one item has been displayed, redo the loop if there are still results } echo "</table>"; I think this is what it is called... I having a brain fart... And I don't play with classes that much... Plus I have been playing with trying to get pdf's to output correctly so my brain is toasty.... I'm trying to parse DICOM (medical file format) files and I have this class and I want to setup an array to pull what fields I want. Code: [Select] <?php require '../dicomparser/nanodicom.php'; $filename = 'B4IBG5A0'; // 5) Load simple and print certain value try { //echo "5) Load simple and print certain value\n"; $dicom = Nanodicom::factory($filename); $dicom->parse(); //echo $dicom->profiler_diff('parse').'<br>'; echo 'Patient Name: '.$dicom->value(0x0010, 0x0010).'<br>'; echo 'Operators Name: '.$dicom->value(0x0010, 0x0040).'<br>'; echo 'Patient ID: '.$dicom->value(0x0010,0x0020).'<br>'; unset($dicom); } catch (Nanodicom_Exception $e) { echo 'File failed. '.$e->getMessage()."\n"; } //} ?> So what I want to do is have the array contain 'Patient Name' => '(0x0010, 0x0010)' etc... And have it something like this so I don't have to echo all the lines I want. Code: [Select] foreach ($array as $key => $value) { echo $key': '.$dicom->value.$value.'<br>'; } I can't get it to work... I remember figuring it out once before but that was over a year ago... And I don't have the code I wrote. I know it's something simple stupid. like $$ or [] i'm not getting the combination right. Thanks in advance... I'm telling it to add 1 each time through the while loop but its not and not sure why. Code: [Select] <fieldset class="answerLeg"> <legend>Edit Poll Answers</legend> <?php $j = 0; while($row2 = mysqli_fetch_array ( $pollAnswersResult, MYSQL_ASSOC )) { ?> <div class="field required answers"> <label for="answer<?php echo ($j + 1)?>">Answer #<?php echo ($j + 1)?></label><input type="text" class="text" name="answer<?php echo ($j + 1)?>" id="answer<?php echo ($j + 1)?>" title="Answer <?php echo ($j + 1)?>" value="<?php echo $row2['answer']; ?>"/> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <?php } ?> </fieldset> After it goes through the while loop its supposed to take the ID of the first one in the loop and find out its awardType and then with the awardType variable go through the the if statement. After it displays it the code that fits the awardType variable then it gets the second item in the while loop and then with the ID of the second item takes it back to get the awardType and then goes back through the if statement again. I'm not sure what I'm doing wrong. As of right now all its doing is displaying its awardName and a blank dropdown. Code: [Select] <?php session_start(); // Access the existing session // Include the database page require ('../../inc/dbconfig.php');l $userID = $_SESSION['userID']; $statusQuery = " SELECT * FROM statuses"; $statusResult = mysqli_query ( $dbc, $statusQuery ); // Run The Query $awardQuery = " SELECT awards.ID, awards.awardName, awards.awardType FROM awards"; $awardResult = mysqli_query ( $dbc, $awardQuery ); // Run The Query $row = mysqli_fetch_array ( $awardResult, MYSQL_ASSOC ); $awardType = $row[ 'awardType' ]; $charactersQuery = " SELECT characters.ID, characters.characterName FROM characters ORDER BY characters.characterName"; $charactersResult = mysqli_query ( $dbc, $charactersQuery ); // Run The Query $matchQuery = " SELECT eventSegments.ID, eventSegments.segmentTitle FROM eventSegments INNER JOIN events ON eventSegments.eventID = events.ID WHERE DATE_FORMAT(events.bookingDate,'%Y') = DATE_FORMAT(curdate(),'%Y')"; $matchResult = mysqli_query ( $dbc, $matchQuery ); // Run The Query ?> Code: [Select] <fieldset> <legend>Nominees</legend> <?php mysqli_data_seek( $awardResult, 0 ); while ( $row = mysqli_fetch_array ( $awardResult, MYSQL_ASSOC ) ) { ?> <?php if ($awardType == 'Singular') { ?> <div class="field required"> <label for="charactersDrop"><?php echo $row['awardName']; ?></label> <select class="dropdown" name="charactersDrop" id="charactersDrop" title="Characters Drop"> <option value="">- Select -</option> <?php while ( $row = mysqli_fetch_array ( $charactersResult, MYSQL_ASSOC ) ) { print "<option value=\"".$row['ID']."\">".$row['characterName']."</option>\r"; } ?> </select> <input type="button" value="Add Character" class="" onclick="HandlerCharacters()"/> <ul id="characterList"> </ul> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <? } else { ?> <div class="field required"> <label for="events"><?php echo $row['awardName']; ?></label> <select class="dropdown" name="events" id="events" title="Events for <?php echo date("Y") ?>"> <option value="">- Select -</option> <?php while ( $row = mysqli_fetch_array ( $matchResult, MYSQL_ASSOC ) ) { print "<option value=\"".$row['ID']."\">".$row['segmentTitle']."</option>\r"; } ?> </select> <input type="button" value="Add Match" class="" onclick="AddMatch()"/> <ul id="matchList"> </ul> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <?php } ?> <?php } ?> I am trying to load all rows from a table in a database into a table on a webpage. I cannot understand why the following code does not work: Code: [Select] <?php ... echo "You are currently in a fleet. The details of the fleet are below.<br>"; $fleetName = $_SESSION['charFleetName']; $sqlFleetDetails = "SELECT * FROM `$fleetName`"; $queryFleetDetails = mysql_query($sqlFleetDetails); echo "<table>"; echo "<tr>"; echo "<th>Pilot</th>"; echo "<th>Ship</th>"; echo "<th>Type</th>"; echo "</tr>"; while($rowFleetDetails = mysql_fetch_array($queryFleetDetails)) { $charId = $rowFleetDetails['charId']; $charName = $rowFleetDetails['charName']; $shipHull = $rowFleetDetails['shipHull']; $shipType = $rowFleetDetails['shipType']; echo "<tr>"; echo "<td><a href=\"#\" onClick=\"CCPEVE.showInfo{1377, " . $charId . "}>" . $charName . "</a></td>"; echo "<td>" . $shipHull . "</td>"; if($shipType == 1) echo "<td>Logistics</td>"; if($shipType == 2) echo "<td>DPS Boat</td>"; if($shipType == 3) echo "<td>Sniper 120Km+</td>"; if($shipType == 4) echo "<td>Off-grid Booster</td>"; echo "</tr>"; } echo "</table><br>"; I originally had the $rowFleetDetails['charId'] and others in the echo instead of loading them into variables then echoing the variables but changed it to see if that was working, neither is. If I add an extra line outside of the while loop to echo the output of the array then the information is displayed fine, so I know that the information is being transferred from the table into the array correctly, but why is it not outputting properly in the While loop? Hi everyone, If you take a look at my code below I am having trouble echoing the key/ value pair of the 'sex' array which is a sub array of 'pens'. I have tried so many different ways but to no avail, thanks Chris! Code: [Select] <?php $products = array( 'paper' => array( 'copier' => "Copier & Multipurpose", 'inkjet' => "Inkjet Printer", 'laser' => "Laser Printer", 'photo' => "Photographic Paper"), 'pens' => array( 'ball' => "Ball Point", 'hilite' => "Highlighters", 'marker' => "Markers", 'sex' => array ( 'condom' => "Protection")), 'misc' => array( 'tape' => "Sticky Tape", 'glue' => "Adhesives", 'clips' => "Paperclips") ); echo "<pre>"; foreach ($products as $section => $items ) foreach ($items as $key => $value) echo "$section:\t$key\t($value)<br>"; echo "</pre>"; ?> HI all, I need help to get data out of an array using a while loop or something simalar. What I have, is this: <?php $data = array( 1 => array( "name" => "Jordan Smith", "age" => "16 Years 0 Months" ), 2 => array( "name" => "Olivia Smith", "age" => "13 Years 12 Months" ) ); Now, what I did, is I constructed this: while($result=$data[1]) { echo $result['name']; } But it echoed "Jordan Smith" for infinity down the page. If anyone can help be do this, it will be great. Thanks I have forum options in a loop (ie value = Entry$i) I need to call GET_POST('Entry$i') and loop though the INSERT query $i times. If I put GET_POST in a loop, however, it does not work. It does not give an INSERT failed error so I assume it is not reading it. I have also tried putting if GET_POST('Entry1') outside the loop, but it does not like it. I dont know how many options are needed so I need it to generate the correct number. Then you can select $i options from duplicated option lists. (Ie) participant 1, 2 and 3 from a list of possibles. I have also use GET_POST, I use a function. Other sumbits (I not use what they are called, please set me know), work fine on this page. Code: [Select] echo "Entry $Number: <select name = \"Entry$j\">"; for ($i = 1; $i<$EntNum+1; $i++) { etc etc then for ($i = 0; $i<$NumberOfEntrys; $i++) { if (isset($_POST['AddEntry']) && isset($_POST["Entry$i"])) //rest of this bit not executed -just insert Ideas? Thanks Now I am stumped this is far any help would be awesome This is what I have gotten so far, this is what it does right now is display the first column of the array as a header for each foreach loop then i've got the data displayed under each header in the loop but what i am trying to understand here is i am trying to get under each header it to have 4 columns or a number of my choosing. Heres an example of what i am trying to do. A airlie beach Andergrove Alexandra Armstrong Beach Alligator Creek B Bucasia Blacks Beach Beaconsfield Bakers Creek Balberra Bloomsbury Breadalbane Ball Bay Belmunda This is an example of how it is being displayed right now A Airlie Beach Andergrove Alexandra Armstrong Beach Alligator Creek B Bucasia Blacks Beach Beaconsfield Bakers Creek Balberra Bloomsbury Breadalbane Ball Bay Belmunda C Cannonvale Calen Crystal Brook Cremorne Chelona Campwin Beach Cape Hillsborough Conway Heres The Code i have so far. Code: [Select] <?php $file = "widget.csv"; @$fp = fopen($file, "r") or die("Could not open file for reading"); $outputArray = array(); while(($shop = fgetcsv($fp, 1000, ",")) !== FALSE) { $outputArray[array_shift($shop)] = array_filter($shop); } print_r($outputArray); echo "\n<br />"; //display echo "<table>"; foreach ($outputArray as $alphabetical=>$value){ echo "<th><b>" . $alphabetical ."</b></th>"; echo "<tr>"; foreach ($value as $key){ echo "<td>" . $key . "</td>"; } echo "</tr>"; } echo "</table>"; echo "\n<br />"; ?> Heres my Csv File which i am using as an array in the code Quote A,Airlie Beach,Andergrove,Alexandra,Armstrong Beach,Alligator Creek,,,,,,,,,,,,,, B,Bucasia,Blacks Beach,Beaconsfield,Bakers Creek,Balberra,Bloomsbury,Breadalbane,Ball Bay,Belmunda,,,,,,,,,, C,Cannonvale,Calen,Crystal Brook,Cremorne,Chelona,Campwin Beach,Cape Hillsborough,Conway,,,,,,,,,,, D,Dows Creek,Dumbleton,Dolphin Heads,,,,,,,,,,,,,,,, E,Eimeo,Eton,Erakala,,,,,,,,,,,,,,,, F,Foulden,Foxdale,Flametree,Farleigh,Freshwater Point,,,,,,,,,,,,,, G,Glen Isla,Glenella,,,,,,,,,,,,,,,,, H,Homebush,Hampden,,,,,,,,,,,,,,,,, I,,,,,,,,,,,,,,,,,,, J,Jubilee Pocket,,,,,,,,,,,,,,,,,, K,Kinchant Dam,Kolijo,Koumala,Kuttabul,,,,,,,,,,,,,,, L,Laguna Quays,,,,,,,,,,,,,,,,,, M,McEwens Beach,Mackay,Mackay Harbour,Mandalay,Marian,Mia Mia,Middlemount,Midge Point,Mirani,Moranbah,Mount Charlton,Mount Jukes,Mount Julian,Mount Marlow,Mount Martin,Mount Ossa,Mount Pelion,Mount Pleasant,Mount Rooper N,Narpi,Nebo,Nindaroo,North Eton,,,,,,,,,,,,,,, O,Oakenden,Ooralea,,,,,,,,,,,,,,,,, P,Palmyra,Paget,Pindi Pindi,Pinevale,Pioneer Valley,Pleystowe,Preston,Proserpine,,,,,,,,,,, Q,,,,,,,,,,,,,,,,,,, R,Racecourse,Richmond,Riordanvale,Rosella,Rural View,,,,,,,,,,,,,, S,St Helens Beach,Sandiford,Sarina,Seaforth,Slade Point,Shoal Point,Shute Harbour,Shutehaven,Strathdickie,Sugarloaf,Sunnyside,,,,,,,, T,Te Kowai,The Leap,,,,,,,,,,,,,,,,, U,,,,,,,,,,,,,,,,,,, V,Victoria Plains,,,,,,,,,,,,,,,,,, W,Wagoora,Walkerston,Woodwark,,,,,,,,,,,,,,,, X,,,,,,,,,,,,,,,,,,, Y,Yalboroo,,,,,,,,,,,,,,,,,, Z,,,,,,,,,,,,,,,,,,, I have a syntax error. I'm not sure what I'm missing. Parse error: syntax error, unexpected ';', expecting ')' Code: [Select] $information = array( $i = 0; while ($i = count($actions)) { array($actions[$i], $action_details[$i]) $i++; } ); Ok so I'll try to explain what I'm trying to do the best I can. I want to build an array that allows me to add/remove/modify the variables used at any point in time without having to rebuild or rewrite a ton of new code. For example, below is an example list of variables I'd like to use in the array, followed by the code I would like to be automatically repeated. Example Variables: $materialName1, $materialName2, $materialName3, $materialName4, $materialName5, $materialName6 etc etc etc Example Code to repeat: Code: [Select] echo "<tr><td>Material: $materialName1</td><td>Rate: $materialName1Rate</td><td>Weight: $materialName1Weight</td></tr>"; Hopefully that makes sense. As always, very appreciated. Iam trying to access amazon API and iam receiving XML perfectly but now I dont know how to traverse all records as in the below example Iam having 3 records but can't travers the xml using foreach Loop Please help me out and tell me how to use foreach loop ?? Its urgent $search="9781439181799,9780393334296,9781605298627"; $result = $obj->getItemByUpc($search, "Books"); foreach($result->children() as $key ) { $data = $key->Items->Request->ItemLookupRequest->ItemId."<br/ >"; echo $data; } Moderator Edit: added [php] tags When a post is approved I only want $details = $_POST['newstitle']; update_user_actions(8, $details); Being posted once with the corresponding news article title. Any way to achieve this? Right now it is looping through all of the titles and is posting them all. Code: [Select] foreach($posts as $post) { $displayName = ucwords("${post['firstname']} ${post['lastname']}"); if (isset($_POST['approve'])) { if(is_array($_POST['approve'])) { $keys = array_keys($_POST['approve']); $id = $keys[0]; $details = $_POST['newstitle']; update_user_actions(8, $details); $sql = "UPDATE `news` SET `newsdate` = NOW(), `approved` = 1 WHERE `id` = '$id'"; header("Location: " . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] ); } } else if (isset($_POST['deny'])) { if(is_array($_POST['deny'])) { $keys = array_keys($_POST['deny']); $id = $keys[0]; $sql = "UPDATE `news` SET `newsdate` = NOW(), `approved` = -1 WHERE `id` = '$id'"; header("Location: " . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] ); } } else if (isset($_POST['delete'])) { if(is_array($_POST['delete'])) { $keys = array_keys($_POST['delete']); $id = $keys[0]; $sql = "DELETE FROM `news` WHERE `id` = '$id'"; header("Location: " . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] ); } } if(isset($sql) && !empty($sql)) { mysql_query($sql) or die(mysql_error()); } ?> I've been getting this error: Fatal error: Maximum execution time of 30 seconds exceeded in... (gives file and line number) I've cut out most of the code in the for loop to narrow it down specifically to the $i variable messing it up somehow... The 2nd part of the if statement where I try to append the $i variable to the new $row_ variable is causing it to hang like this. I want to be able to make 5 new variables... $row_1...$row_2...etc... but for some reason when I try to append the $i to it, it hangs. and throws that error eventually. Does anyone know why it does this? Any help is appreciated. Thank you! Code: [Select] for ($i=1;$i<6;$i++){ if ($row['bef_remarks' . $i] != "Description"){ $row_.$i = 1; I'm trying to create a series of functions, when activated: a. scans a target directory for jpg's -> returns file names to an array b. takes those file names and stripes the .jpg from them -> return file name, extension, and full filename c. inserts said file names into a MySQL database Here's the problem: The second function won't loop on the return array('name' => $name), it just does it once. Code: Function 1 (of 3) Code: [Select] function scanJpg($phpath){ $dir = opendir($phpath); while(false !== ($file = readdir($dir))){ if($file != "." && $file != ".."){ if(!is_dir($phpath.$file)){ $results[] = $file; } } } closedir($dir); return $results; } // returns // Array ( [0] => lakeonrefuge.jpg [1] => shasta04.jpg [2] => carly_lol.jpg [3] => beach_adventures_florence.jpg [4] => beach_adventures.jpg [5] => Beach-0168.jpg ) function 2 Code: [Select] function stripJpg($jpgs,$phpath){ foreach($jpgs as $jpg){ $ext = strrchr($jpg, '.'); if($ext !== false) { $name = substr($jpg, 0, -strlen($ext)); echo $name."<br />"; echo $jpg."<br />"; echo $ext."<br /><br />"; return array( 'name' => $name, 'filename' => $jpg, 'ext' => $ext ); } } } ## $jpgs = scanJpg($phpath); ## print_r(stripJpg($jpgs,$phpath)); ## ## returns the following ## Array ( [name] => lakeonrefuge [filename] => lakeonrefuge.jpg [ext] => .jpg ) What am I overlooking? Thanks in advance! I think the problem is with echo "<td>".$row["countnow($i)"]."</td>"; it's not showing anything, any ideas how to fix it? Code: [Select] $i = 1; While ($i <25) { ?> <tr> <td><?php echo $i; ?></td> <?php $sql = "SELECT * FROM `systems` WHERE `solarSystemName` LIKE $sname" or die (mysql_error()); $result = mysql_query($sql); while ($row = mysql_fetch_array($result)){ echo "<td>".$row["countnow($i)"]."</td>"; } ?> <tr> <?php $i++; } Hello everyone. I am new to PHP, and to programming in general. As of right now, I am reading and learning from "Learning PHP and MySQL" by Michele E. Davis and Jon A. Phillips. In the 'for' loop section of chapter 4, the example they give that actually works, is: Code: [Select] <?php for ($num = 1; $num <= 10; $num++) { print "Number is $num<br />\n"; } ?> A question at the end of the chapter requests that I make a 'for' loop counting from 10 to 1. I wrote it as follows: Code: [Select] <?php for ($num = 10; $num >= 10; $num--){ print "Number is $num<br />"; } ?> For some reason, my code does not execute, but their example above does. When I checked the appendix answer for creating a 'for' loop counting from 10 to 1, this is the answer the appendix provides: Code: [Select] <?php for ($num = 10; $num >= 1; $num&#8722;&#8722;){ print "$num<br>; } ?> For some reason, the 3rd expression in the code above is not showing up correctly, but it reads, "$num−−" if that helps. I don't agree with the appendix, being that it looks radically different than the example used in the chapter, and i have no idea how to decipher the 3rd expression in the for loop. Can someone tell me what I am doing wrong? I have never used cURL before but I need to use it for developing a facebook application. What I am trying to do is create a status update scheduler. There are two tables in my database. One table has generic updates for each day of the week an the other had special events. My script checks the day, checks to see if there is a special event in the future on that day, and if there is reminds guests of the upcoming event. If there is no event it posts the generic status. Code: [Select] <?php include('config.php'); $result2 = mysql_query("select facebook_id,facebook_access_token from admin where username='users'"); $row = mysql_fetch_array($result2); $facebook_id = $row['facebook_id']; $facebook_access_token = $row['facebook_access_token']; $day = date('N'); $result2 = mysql_query("select * from events where date > CURDATE() order by date ASC") or die(mysql_error()); $num_rows = mysql_num_rows($result2); if($num_rows == 0) { $result2 = mysql_query("select * FROM alerts WHERE id='$day'") or die(mysql_error()); $row1 = mysql_fetch_array($result2); echo 'There are no events just alerts'; } else { while($row = mysql_fetch_array($result2)){ if(date('N',strtotime($row[date])) == $day) { $id = $row['id']; $result1 = mysql_query("SELECT * FROM events WHERE id = $id") or die(mysql_error()); $row1 = mysql_fetch_array($result1); } else { $result1 = mysql_query("SELECT * FROM alerts WHERE id = $day") or die(mysql_error()); $row1 = mysql_fetch_array($result1); } } } $params = array('access_token' => $facebook_access_token, 'message' => $row1[alert_message], 'name'=> $row1[alert_name], 'caption' => $row1[alert_caption], 'link' => $row1[alert_link], 'description' => $row1[alert_description], 'picture' => $row1[alert_picture] ); $url = "https://graph.facebook.com/$facebook_id/feed"; $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_URL => $url, CURLOPT_POSTFIELDS => $params, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_VERBOSE => true )); $result = curl_exec($ch); ?> The problem seems to be occurring when the While loop is accessed. I have used 'echo' to follow the variables through the script and it all seems to be working. However if I try and execute the cURL and the While Loop has run then it does not seem to work. I know the cURL part works becuase if the variables cause the first IF statement default to ELSE then it runs fine. Any help would be GREATLY appreciated. Hi there, im trying to nest two do loops. The first loop works fine but the last loop doesnt seem to work at all. Code: [Select] <? $colname_Planet = "-1"; if (isset($_GET['recordID'])) { $colname_Planet = (get_magic_quotes_gpc()) ? $_GET['recordID'] : addslashes($_GET['recordID']); } mysql_select_db($database_swb, $swb); $query_Planet = sprintf("SELECT * FROM planet WHERE PlanetName = %s", GetSQLValueString($colname_Planet, "text")); $Planet = mysql_query($query_Planet, $swb) or die(mysql_error()); $row_Planet = mysql_fetch_assoc($Planet); $totalRows_Planet = mysql_num_rows($Planet); $plans = $row_Planet['PlanetName']; $colname_Fleet = "-1"; if (isset($_GET['recordID'])) { $colname_Fleet = (get_magic_quotes_gpc()) ? $_GET['recordID'] : addslashes($_GET['recordID']); } mysql_select_db($database_swb, $swb); $query_Fleet = sprintf("SELECT * FROM fleet WHERE PlanetName = '$plans'"); $Fleet = mysql_query($query_Fleet, $swb) or die(mysql_error()); $row_Fleet = mysql_fetch_assoc($Fleet); $totalRows_Fleet = mysql_num_rows($Fleet); $fleetships = $row_Fleet['FleetName']; $colname_Ships = "-1"; if (isset($_GET['recordID'])) { $colname_Ships = (get_magic_quotes_gpc()) ? $_GET['recordID'] : addslashes($_GET['recordID']); } mysql_select_db($database_swb, $swb); $query_Ships = sprintf("SELECT * FROM ships WHERE FleetName = '$fleetships'"); $Ships = mysql_query($query_Ships, $swb) or die(mysql_error()); $row_Ships = mysql_fetch_assoc($Ships); $totalRows_Ships = mysql_num_rows($Ships); ?> <?php do { ?> <?php echo $row_Fleet['FleetName']; ?> <?php echo $row_Fleet['PlanetName']; ?> <?php do { ?> <?php echo $row_Ships['ShipName']; ?> <?php } while ($row_Ships = mysql_fetch_assoc($Ships)); ?> <?php } while ($row_Fleet = mysql_fetch_assoc($Fleet)); ?> If you can spot anything wrong, please let me know. Thanks I have this query which query the parent.name and the node.name as well. Code: [Select] "SELECT parent.name FROM categories AS node, categories AS parent WHERE node.left_node BETWEEN parent.left_node AND parent.right_node AND node.name = '{$node_name}' ORDER BY parent.right_node AND node.left_node" below in the foreach loop is displaying both the node and parent, I only need the parent. I have done a little if statement saying that if node.name not to display but didn't work because both parent.name and node.name are displaying the he same field name. Code: [Select] <?php foreach($iterator as $key=>$value) { if($value <> "node.name") echo $value.'<br />'; } ?> $array = array("1","2","3"); foreach ($array as $value){ echo $value; } Put its only echoing out 3, not the whole array. ok guys, im going out the door so forgive me for not showing any code..but I have a while loop whithin a while loop to display rows for two different id's. I have a mysql_num_rows vaiable set that displays 0 because there are 0 rows with the userid of 1...then it displays 2 because there are 2 rows with the userid of 3..now what i want to do is find a way to omit the return of 0 so that i can use the return of 2 alone. sorry if im not clear enough. Code: [Select] <?php $hierachy = new hierachy; $iterator = new RecursiveIteratorIterator(new recursiveArrayIterator($hierachy->getLocalSubNodes($name1))); try { foreach($iterator as $key=>$value) { echo $value = substr($value,0,-1).'<br />'; } } catch(Exception $e) { echo $e->getMessage(); }?> this is only returning one record, when I know there are more, and it's an endless loop crashing my browser, can someone tell me how my brackets are wrong, or what is wrong? Code: [Select] if (isset($_POST['search'])){ $keyword=$_POST['keyword']; } $sql="SELECT id, fname, lname FROM obituaries WHERE lname LIKE '%$keyword%' OR fname LIKE '%$keyword%' ORDER BY id DESC"; $results = mysql_query($sql); $num = mysql_num_rows ($results); if ($num > 0 ) { $i=0; while ($i < $num) { $id = mysql_result($results,$i,"id"); $fname = mysql_result($results,$i,"fname"); $lname = mysql_result($results,$i,"lname"); ?> <a href="view.php?id=<?php echo ($id); ?>"><?php echo($fname); ?> <?php echo($lname); ?></a> <?php } } ?>Thanks in advance how would i loop the below script so that more than one file can be uploaded. my form lets you select more than one image but i am not sure how to loop the below. Code: [Select] if( isset($_POST['submit']) ) { include('thumbnail.php'); $userfile = $_FILES['uploaded_image']['name']; $file_size = $_FILES['uploaded_image']['size']; $file_temp = $_FILES['uploaded_image']['tmp_name']; $file_err = $_FILES['uploaded_image']['error']; $folder = $_POST['folder']; $path = "../../gallery/gallery_files/gallery/$folder/"; $path1 = "../../gallery/gallery_files/gallery/$folder/thumbnails/"; $image = new SimpleImage(); $image->load($file_temp); $image->resizeToWidth(600); $image->save($path.$userfile); $image->resizeToWidth(110); $image->save($path1.$userfile); } else { } I need help this problem seem too tricky for me right now. I got an array with decimal numbers and behind it says Yes/No. The min() function works magically and still is able to correctly give me the lowest value. But how do i make a while loop that loops until it pops a value that is lowest and has Yes behind it? For example: Array => ('11,64|No', '209,81|Yes', '533,42|Yes', '27,90|No', '93,01|Yes') So this function should return '93,01|Yes' Hi guys, Was wondering if anyone can help me with this. Here's what I'm trying to do: I've retrieved values from table a from mysql and post them on a form. Code: [Select] echo "<tr><td>" .$row['id']. "</td><td>" .$row['name']. "<input type='hidden' name=name[] value=" .$row['name']. "></td><td><select name='item[]'><option value ='' selected='selected'>Please Select</option><option value ='1'>1</option><option value ='2'>2</option><option value ='3'>3</option></td></tr>"; and now i'm trying to display these information one more time on a different page. So I did the usual retrieval Code: [Select] $name = $_POST['name']; $item = $_POST['item']; Then I'm using foreach loop to retrieve the item values. Code: [Select] foreach ($item as $getitem => $value) { echo "<tr><td>"; echo $value; echo "</td></tr>"; } Here is where I'm stumped. What's the best way to associate the name to the item. while loop? Thanks for the help. I'm not sure what PHP considers an "aborted connection" and things like that, but the way this chat works is by updating a file and using the timestamp off it to determine if new posts exist. Rather than re-checking the server over and over, this code will check once and keep the connection open until a response is made. The only problem is, it works too well! Even after the tab is closed and I try another script on the site or the same script, it all hangs until I update the file - here is the code snippet: while (($currentmodif <= $lastmodif) && (connection_aborted() == 0) && (connection_status() == 0)){ // check if the data file has been modified usleep(10000); // sleep 10ms to unload the CPU if (connection_aborted ()) break; if (connection_status () != 0) break; clearstatcache(); $currentmodif = filemtime($filename); } I have put several measures in to attempt to break the loop when the user disconnects, but it just doesn't work! It will continue to hang and hang and hang until I re-upload the file $filename HOW CAN I BREAK THE WHILE LOOP WHEN THE MEMBER LEAVES THE PAGE? I could post up an example but its ultimately useless after one load unless you have control over updating the file. Thanks! The 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; } This is probably a simple question, but if you are looping through a while loop using an if - else statement why would it echo the answer the amount of times there are data fields? Like if you had three users in a database and you had an if statement to validate a user name and password. If the user name and password passed it would say good - if it failed it would say no good. But instead it prints - good no good good, or no good good good, ect.??? Ok, I'm having some trouble with file_get_contents failing & am trying to make a loop that will sleep & then retry a maximum of 3 times before giving up & moving to the next item. I tried using a while loop but I'm getting unexpected T_WHILE, which I assume is because it's already in a while loop? I found this: Code: [Select] $maxTries = "3"; for ($try=1; $try<=$maxTries; $try++) { but could use some clarification. Will that only trigger if it failes or do I need to include another if statement like Code: [Select] $myfile = file_get_contents("http://example.com"); if ($myfile === FALSE) { $maxTries = "3"; for ($try=1; $try<=$maxTries; $try++) { sleep(3); $myfile = file_get_contents("http://example.com"); } else { //continue with script I hope that makes sense...trying to explain it as best I can without having to post my actual source code as I've had it stolen off forums before & now I have a clone to compete with. I'm not great at putting this into words so if I need to clarify, please feel free to ask. I appreciate any & all help given. Thanks! Hi, first of all thanks in advance for the help. I'm a newbie college student and am having a little problem with a project for a class that I can't figure out. I'm trying to construct a loop that creates an array for a javascript image gallery. First I call for the categories and I want to then pull all the images from that category into the array and then loop through all the categories in the database. The code below just cycles through the first category and then quits after pulling the images from that category. Code: [Select] <?php // SQL Query for Categories $sql="SELECT CategoryID, CategoryName FROM pro2category"; $result = mysql_query($sql); if(empty($result)) { $num_results = 0; } else { $num_results = mysql_num_rows($result); } ?> <?php for($i=0; $i<$num_results; $i++) { $row = mysql_fetch_array($result); $CategoryID = $row["CategoryID"]; $CategoryName = $row["CategoryName"]; ?> var <?php echo $CategoryID ?> = new Array(); <!-- Images inside Array --> <!-- Images inside Array --> <!-- Images inside Array --> <!-- Images inside Array --> <?php $sql="SELECT ImageID, ImageName, ImageNumber, URL, CategoryID FROM pro2image WHERE CategoryID='$CategoryID'"; $result = mysql_query($sql); if(empty($result)) { $num_results = 0; } else { $num_results = mysql_num_rows($result); } ?> <?php for($i=0; $i<$num_results; $i++) { $row = mysql_fetch_array($result); $ImageID = $row["ImageID"]; ?> <?php echo $CategoryID ?>Array[<?php echo $i ?>] = "http://cgtweb2.tech.purdue.edu/356/zrodimel/Project2/admin/upload/<?php echo $ImageID ?>.jpg"; <?php } ?> <?php } ?> thanks for the help Zach Hey guys, I couldn't really think of a decent topic title for this but I hope by the end of it you'll know what I mean. Brief background: I work in an IT department in a school. I am in the process of writing a page to show room and resource booking for the current day and for the next day. There are six blocks that bookings can be made (before school, periods one-four, after school). I have written a query to display all the bookings for a given day. I have looped the six available periods to it has a header for them, and have done the same for containers for the bookings. What I am having problems with is getting it to show under the correct period for the start time and end time for the booking. For example, if a booking starts and ends period three, I want it to show just for period three. If it is a daily booking, it goes on all day. My query is this and I am happy with it - phpmyadmin display everything I want and the start time and end time are correct. Code: [Select] ( SELECT `bno` AS `bookingid`, UPPER(`whofor`) AS `name`, `timestart`, `timeend`, `where` AS `room`, '' AS `comments`, TRIM(TRAILING '||' FROM `What1`) AS `equipment`, IF(`date` = '1', '1', '1') AS `type` FROM `booked` WHERE UNIX_TIMESTAMP(CONCAT_WS('-', `year`, `month`, `day`)) = '{$time}' AND `active` = 'yes' AND `timestart` != 'all' ) UNION ( SELECT `bno` AS `bookingid`, UPPER(`whofor`) AS `name`, '1' AS `timestart`, '6' AS `timeend`, `where` AS `room`, '' AS `comments`, TRIM(TRAILING '||' FROM `What1`) AS `equipment`, IF(`date` = '1', '1', '1') AS `type` FROM `booked` WHERE UNIX_TIMESTAMP(CONCAT_WS('-', `year`, `month`, `day`)) = '{$time}' AND `active` = 'yes' AND `timestart` = 'all' ) UNION ( SELECT `bid` AS `bookingid`, UPPER(`name`), `period`, `period`, IF(`room` = '8', 'Lower Laptops', 'Middle Laptops') AS `room`, `comments` AS `comments`, '', IF(`timebooked` = '2', '2', '2') AS `type` FROM `bookedrooms` WHERE UNIX_TIMESTAMP(CONCAT_WS('-', `year`, `month`, `day`)) = '{$time}' AND `room` IN(8,9) AND `name` != 'not available' AND `active` = 'yes' ) ORDER BY `timestart`, `type` ASC $time = (isset($_GET['tomorrow'])) ? strtotime('tomorrow 00:00') : strtotime('today 00:00'); Just wondering if anybody here has ever done anything similar to this to give me a hand. Thanks in advance! |