PHP - For Each Loop Issue!!!
I'm starting to get peeved with PHP today, after many hours of trying to sort an issue - I'm sure you all know what I mean.
Once again, the issue lies with foreach loops which I have never been able to fully understand, especially when dealing with multiple arrays. The code is for a CMS, where a restaurant owner can update his menu's and choose whether to show them on the website using a tick box. Here's a screenshot.. Essentially, the issue I am having is should I click say, the bottom tickbox and click Update it will for some reason, tick the second in the database.... In reverse, if all are ticked, and I untick the bottom, it will untick the box before it.... it is sooo frustrating.. From what I can see, it is likely to be where the array, where ticked boxes have a value, and non-ticked ones don't... but I tried to sort this in my foreach loop setting an empty value to off.... Here is the HTML code: Code: [Select] <form action="./includes/scripts/menus/update.php" enctype="multipart/form-data" method="post"> <button type="submit" onclick="return confirm('Updating Menu Changes...\n\nUpdating PDF files may time some time.. \n\nDo not navigate away from this page until you recieve a success or failure confirmation.\n\nClick Cancel to make changes.'); { return alert('noob'); }">Update Menu Changes</button> <button type="button" onClick="document.location.href='./includes/scripts/menus/new_row.php'">Add New Menu Item...</button> <br /><br /> <table border="0" width="962" cellpadding="0" cellspacing="0"> <tr style="padding-bottom: 3px;"> <th style="text-align: center;" width="195.4">Active</th> <th style="text-align: center;" width="195.4">Menu</th> <th style="text-align: center;" width="195.4">Current Menu</th> <th style="text-align: center;" width="195.4">Change Menu (PDF format only)</th> <th style="text-align: text-align: center;" width="195.4">Tasks</th> </tr> <? $query = "SELECT * FROM menus ORDER by id ASC"; $query = mysql_query($query) or die(mysql_error()); //Count rows $num_rows = mysql_num_rows($query); //If no rows exist if($num_rows=="0") { ?> <tr style="padding-bottom: 3px;"> <td colspan="4" style="text-align: center;">There are currently no menus listed in the Pen Mill Hotel database.</td> </tr> <? } //If new rows exist elseif($num_rows!=="0") { $i = "0"; while($row=mysql_fetch_array($query)) { //Database Variables $name = $row["menu"]; $id = $row["id"]; $location = $row["location"]; //Establish if a menu is present in database for current entry if(empty($location)) { $current = "<a style=\"cursor: pointer;\" onclick=\"alert('No menu found!');\" title=\"View Listed Menu\">View Current Menu</a>"; } elseif(!empty($location)) { $current = "../includes/menus/" . $row["location"]; $current = "<a href=\"$current\" title=\"View Listed Menu\" />View Current Menu</a>"; } //Establish whether to check tickbox or not. $active = $row["active"]; if($active=="on") { $active = " checked=\"checked\" "; } elseif($active!=="on") { $active = " "; } ?> <tr style="padding-bottom: 3px;" id="<? echo "$id"; ?>"> <td style="text-align: center;"> <input type="checkbox"<? echo "$active"; ?>name="active[<? echo "$i"; ?>]" /> </td> <td style="text-align: center;"> <input type="text" style="padding: 0px;" name="name[]" value="<? echo "$name"; ?>" /> </td> <td style="text-align: center;"> <? echo $current; ?> </td> <!-- Tell PHP, max file size is equal to 5MB (in bytes) --> <input type="hidden" name="MAX_FILE_SIZE" value="5242880" /> <td style="text-align: center;"><input type="file" name="menu_file[]" /></td> <td style="text-align: center;"> <a href="./includes/scripts/menus/delete.php?id=<? echo "$id"; ?>" onclick="return confirm('Are you sure you wish to delete this menu?\n ');"> Delete </a> </td> </tr> <input type="hidden" name="id[]" value="<? echo $id; ?>" /> <? $i++; ?> <? } } ?> </table> <br /> <button type="submit" onclick="return confirm('Updating Menu Changes...\n\nUpdating PDF files may time some time.. \n\nDo not navigate away from this page until you recieve a success or failure confirmation.\n\nClick Cancel to make changes.');">Update Menu Changes</button> <button type="button" onClick="document.location.href='./includes/scripts/menus/new_row.php'">Add New Menu Item...</button> </form> And here is the PHP, baring in mind it will also deal with a file upload, but that isn't the issue at the moment... Code: [Select] <? /* This script is for use on the Manage Menu's pages and updates all menu items. */ /*==================================*/ /* DATE BASE CONFIGURATION */ /*==================================*/ include_once "../../config/config.php"; /*==================================*/ /* SET VARIABLES */ /*==================================*/ $id = $_POST["id"]; $active = $_POST["active"]; $name = $_POST["name"]; $menu_file = $_FILES['menu_file']; $i = "0"; /*==================================*/ /* Loop Each Menu & Update */ /*==================================*/ foreach($id as $key) { //Set Sub Variables if(empty($active["$i"])) { $active["$i"] = "off"; } $active_post = $active["$i"]; $name_loop = $name["$i"]; //Set File Variables $file_name = $menu_file["name"]["$i"]; //name of file on users machine $file_type = $menu_file["type"]["$i"]; //type of file being uploaded $file_size = $menu_file["size"]["$i"]; //size of the uploaded file in bytes $file_error = $menu_file["error"]["$i"]; //returned PHP error codes for upload $file_temp = $menu_file["tmp_name"]["$i"]; //temporary name on server //Handle Uploaded File (if uploaded) if(!empty($file_name)) { //FILE ERROR CHECKS //If file type is not PDF. if($file_type!=="application/pdf") { $pass = "0"; header("Location: ../../../index.php?page=Menus&error=Incorrect_File_Type"); } //If file type is greater than 5MB. if($file_size>"5242880") { $pass = "0"; header("Location: ../../../index.php?page=Menus&error=Incorrect_File_Size"); } //If above error checks pass if($pass!="0") { //Get todays date for file rename $today = date("d-m-Y"); $uploaddir = "/home/penmillh/en/includes/menus/"; $upload_name = str_replace(" ", "", $name_loop) . $today . ".pdf"; $uploadfile = $uploaddir . $upload_name; //Move file only if PHP upload status is correct if($file_error!="UPLOAD_ERR_OK") { header("Location: ../../../index.php?page=Menus&error=File_Upload_Error"); } //If PHP status is okay, upload file and update table. if($file_error=="UPLOAD_ERR_OK") { //Upload move_uploaded_file($file_tmp, $uploadfile); //Update Database $query = "UPDATE menus SET active='$active', menu='$name_loop', location='$upload_name' WHERE id='$value'"; $query = mysql_query($query) or die(mysql_error()); header("Location: ../../../index.php?page=Menus&error=File_Upload_Success"); } } } //If no uploaded file, update database records if(empty($file_name)) { //Update Database $query = "UPDATE menus SET active='$active_post' WHERE id='$key'"; $query = mysql_query($query) or die(mysql_error()); // header("Location: ../../../index.php?page=Menus&error=Menu_Change_Success"); } $i++; } ?> Now, I have probably made this INCREDIBLY complicated, but that's all I could remember from my previous experience with foreach loops.... Any ideas? Similar TutorialsIm trying to search through the read column and see if any of the rows are read I echo $mail and it shows all the rows for the user. So im grabing the ones I want but now i dont know how to search through what I selected. Or is there a simplier way of having SQL do what im trying to do? Code: [Select] <?php $query = "SELECT `read` FROM pm WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'"; $results = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_assoc($results)) { $mail = $row['read']; } // checks if user has unread mail or not if ($mail == "unread") { echo '<td><b><a href="inbox.php?inbox=1">Messages</a></b></td><td id="diamond">♦</td>'; } else { echo '<td><a href="inbox.php?inbox=1">Messages</a></td>'; } ?> The first run of my for loop does not execute, but all after that works. I know I need to define my $strings before the for loop because they do not take effect until it has ran once and that is why it does not show the first run. But I don't completely understand how to solve the issue, and have tried everything to my knowledge. The code below imports a steam group page xml and gets the unique ids for each of the groups members, then retrieves information about members. <?php $groupxml = simplexml_load_file('http://steamcommunity.com/groups/MDK-Society/memberslistxml/?xml=1'); $members = $groupxml->memberCount; $array = $groupxml->members->steamID64; for($arraycount="0"; $arraycount<$members; $arraycount=$arraycount+1){ $xml = simplexml_load_file("http://steamcommunity.com/profiles/$array[$arraycount]/?xml=1"); echo "<a href=\"#\" title=\"<img src=$xml->avatarMedium align=right /> $xml->steamID<br />$xml->stateMessage<br /><br />Location: $xml->location<br />$xml->summary\"><img src=\"$xml->avatarMedium\" /></a>"; echo "<br>"; if ("$xml->onlineState" == "online") { echo "<img src=\"images/stateonlinemaster.png\" />"; } elseif ("$xml->onlineState" == "offline") { echo "<img src=\"images/stateofflinemaster.png\" />"; } else { echo "<img src=\"images/stateingamemaster.png\" />"; } echo "<br>"; echo "<br>"; } ?> Could you explain to me fully where I went wrong in the for loop. Thanks Hello, I have a page where the user uploads a CSV file and I want to read that CSV and update database fields accordingly. It seems I have all the code correct but only the first row of the CSV is being imported. If I echo my variables within the loop, the only output is the first row of the CSV - no subsequent rows. I feel like I'm close but not sure what the issue is? Thanks a million for any help!! Jason //START FILE OPERATION $handle = fopen('uploads/testfile.csv', "r"); //LOOP CONTENTS OF CSV FILE while (($data = fgetcsv($handle, 1000, ",")) !== false) { $importID = $data[0]; $companyName = $data[1]; $primaryPhone = $data[2]; $primaryEmail = $data[3]; $billingFirstName = $data[4]; $billingLastName = $data[5]; $query = 'SELECT importID FROM import'; if (!$result = mysql_query($query)) { continue; } if ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { //UPDATE IF ENTRY EXISTS $query = "UPDATE import SET companyName='$companyName', primaryPhone='$primaryPhone', primaryEmail='$primaryEmail', billingFirstName='$billingFirstName' WHERE importID=$importID"; mysql_query($query); if (mysql_affected_rows() <= 0) { //NO RECORDS UPDATED } } else { //ENTRY DOESN'T EXIST } mysql_free_result($result); } //CLOSE FILE OPERATION fclose($handle); Hi all. How do I loop the below script? $query_basket = mysql_query("SELECT * FROM `store_basket` WHERE sessionid='".$sessionid."'"); $rows = mysql_num_rows($query_basket); $r = mysql_fetch_array($query_basket); $allitems = $rows; while($result_basket = mysql_fetch_array($query_basket)) { $price_without_tax = $result_basket['price']; $tax = 17.5; $price_with_tax = $result_basket['price'] + $tax; $price_times_qty = $result_basket['price'] * $result_basket['qty']; $basket_item = $result_basket['item']; $basket_qty = $result_basket['qty']; $basket_initial1 = $result_basket['initial1']; $basket_initial2 = $result_basket['initial2']; $basket_initial3 = $result_basket['initial3']; } if($allitems == 1) { $basket .= $allitems.":".$basket_item." ".strtoupper($basket_initial1)."-".strtoupper($basket_initial2)."-".strtoupper($basket_initial3).":".$basket_qty.":".$price_without_tax.":".$tax.":".$price_with_tax.":".$price_times_qty; } else { $allitems = $rows; $basket .= ":".$basket_item." ".strtoupper($basket_initial1)."-".strtoupper($basket_initial2)."-".strtoupper($basket_initial3).":".$basket_qty.":".$price_without_tax.":".$tax.":".$price_with_tax.":".$price_times_qty; } Basically if there is more than one row I need to loop the $basket string so that it shows the values for each item. Thanks Pete Hey guys, I am using php loop to echo out all off the data in my database category within a html table. However I would like to reduce each table row to only 5 results then start a new row so that the table fits within the webpage. Any suggestions? Any help is much appreciated. Thanks. Jason Here is what i am using, but does not fit within the page. Code: [Select] <table cellspacing="10"> <tr> <?php $query = mysql_query('SELECT photo_id, photo_name FROM gallery_photos WHERE photo_category = "Books" AND photo_approved = 1 ORDER BY rand()'); while ($row = mysql_fetch_array($query)) { echo "<td><a href='http://www.mysite.com/view.php?pid=".$row['photo_id']."'><img src='photos/".$row['photo_id'].".jpg' width='115' height='115' /><center><h3><b>".$row['photo_name']."</b></h3></center></a></td>"; } ?> </tr> </table> I am trying to recursively pull records from a database to write to a csv. There are three test rows of data in my table (and no not including the table headers). The only issue is i can’t seem to get my for loop to display all the records – it only displays the last 2 rows so i’m very confused. Anyone suggest why this isn’t working? Code: [Select] $num_rows = mysql_num_rows($export); for ($i=0; $i <= $num_rows; $i++ ) { $row = mysql_fetch_row($export); echo $row[1] . $row[2] . $row[3] . $row[4] . $row[5] . $row[6] ."<br/>"; echo $i; } Incidentally the query is just a fetch all from datasbase. Anyone see where i'm going wrong? Thanks, drongo Hey there folks, Im trying to get a foreach loop working correctly from a json source epg heres my code: https://pastebin.com/FjHj1EF6 Here is the current output, which.. while correct is only the first instance of these values i wanted using the foreach loop, i would love any tips on why my approach failed and to be pointed in the right direction. While it has to be included: $url = "https://mywebsite.fake/mlb.php?id={$arr['games'][0]["gamePk"]}"; this value isn't related to the assistance im asking for. that will work for my purposes later. but for now i just need to understand the issue with the foreach loop. Thanks in advance for your thoughtful response. mosb3rgler Let me explain my problem. I have an array with dates and numbers in format ($cronograma) Ex: Array ( [2020-09-21] => Array ( [0] => 2020-09-21 [1] => 2 [2] => 2 [3] => 2 ) [2020-09-28] => Array ( [0] => 2020-09-28 [1] => 2 [2] => 2 [3] => 4 ) Then i have another array with 2 ids (in this case 58,60) ($id) Finally i have a third array with numbers only (in this case 34,34) $tot So what i want is cross information beween them, for example for id 58 I must get dates (first element and last element when $tot = 34) for id 60 I must get dates (first element after $tot =34 and last element of array) Whath i have so far is this foreach ($id as $idPlan) { foreach ($cronograma as $c) { $t1 = 0; foreach ($tot as $d) { $t1 += (int)$d['tempos']; if ($c[3] == $t1) { $newAr[] =$idPlan; $newAr[] = $c[0]; } } } } My response array(8) { [0]=> string(2) "58" [1]=> string(10) "2021-02-01" [2]=> string(2) "58" [3]=> string(10) "2021-06-14" [4]=> string(2) "60" [5]=> string(10) "2021-02-01" [6]=> string(2) "60" [7]=> string(10) "2021-06-14" } null So it's clear that i have all repeated I should have a line like: 58 - 2020-09-21 -2021-02-01 Any help? can anybody tell me what's wrong with my query ? $filesa = "SELECT id, uid, size, filehash, filename, dwnloads, swidth, sheight, fores, flabel, vpre FROM pf_fmusic WHERE (aid='$albumid' AND vpre='complete') ORDER BY id DESC"; I am using this in while loop with ps_pagination class but getting 2 records for same set of files. in other words its running while loop 2 time complete code is here... $filesa = "SELECT id, uid, size, filehash, filename, dwnloads, swidth, sheight, fores, flabel FROM ibwf_fmusic WHERE (aid='$albumid' AND vpre='complete') ORDER BY id DESC"; $pager = new PS_Pagination($conn, $filesa, 9, 5, $albumid, $sortid, $sub, $selectalbum3[uid], $title, $collective); $results = $pager->paginate(); while($files=mysql_fetch_array($results)) { // Blah Blah } Output is something like this 1. song 1 2. song 2 3. song 3 4. song 4 1. song 1 2. song 2 3. song 3 4. song 4 Thanks is advance 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? Below is my output on the browser: Student: Kevin Smith (u0867587) Course: INFO101 - Bsc Information Communication Technology Course Mark 70 Grade Year: 3 Module: CHI2550 - Modern Database Applications Module Mark: 41 Mark Percentage: 68 Grade: B Session: AAB Session Mark: 72 Session Weight Contribution 20% Session: AAE Session Mark: 67 Session Weight Contribution 40% Module: CHI2513 - Systems Strategy Module Mark: 31 Mark Percentage: 62 Grade: B Session: AAD Session Mark: 61 Session Weight Contribution 50% Now where it says course mark above it says 70. This is incorrect as it should be 65 (The average between the module marks percentage should be 65 in the example above) but for some stange reason I can get the answer 65. I have a variable called $courseMark and that does the calculation. Now if the $courseMark is echo outside the where loop, then it will equal 65 but if it is put in while loop where I want the variable to be displayed, then it adds up to 70. Why does it do this. Below is the code: Code: [Select] $sessionMark = 0; $sessionWeight = 0; $courseMark = 0; $output = ""; $studentId = false; $courseId = false; $moduleId = false; while ($row = mysql_fetch_array($result)) { $sessionMark += round($row['Mark'] / 100 * $row['SessionWeight']); $sessionWeight += ($row['SessionWeight']); $courseMark = ($sessionMark / $sessionWeight * 100); if($studentId != $row['StudentUsername']) { //Student has changed $studentId = $row['StudentUsername']; $output .= "<p><strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']})\n"; } if($courseId != $row['CourseId']) { //Course has changed $courseId = $row['CourseId']; $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <strong>Course Mark</strong>" round($courseMark) "<strong>Grade</strong> <br><strong>Year:</strong> {$row['Year']}</p>\n"; } if($moduleId != $row['ModuleId']) { //Module has changed if(isset($sessionsAry)) //Don't run function for first record { //Get output for last module and sessions $output .= outputModule($moduleId, $moduleName, $sessionsAry); } //Reset sessions data array and Set values for new module $sessionsAry = array(); $moduleId = $row['ModuleId']; $moduleName = $row['ModuleName']; } //Add session data to array for current module $sessionsAry[] = array('SessionId'=>$row['SessionId'], 'Mark'=>$row['Mark'], 'SessionWeight'=>$row['SessionWeight']); } //Get output for last module $output .= outputModule($moduleId, $moduleName, $sessionsAry); //Display the output echo $output; I think the problem is that it is outputting the answer of the calculation only for the first session mark. How in the while loop can I do it so it doesn't display it for the first mark only but for all the session marks so that it ends up showing the correct answer 65 and not 72? Hey guys, Got another question im hoping someone can help me with. I have a foreach loop (for use in a mysql query): foreach ($interests as $interest) { $query .= "($id, $interest), "; } problem is i do not want the comma(,) in the last loop. Is there some kinda of function i can use so it does not insert it on last loop? Or should i just use a for loop with a nested if loop? something like ; for($i=0; $i < count($interests); $i++){ $query .= "($id, '$interests[$i]')"; if($i + 1 < count($interests)) { $query .= ", "; } } Cheers guys 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 Good Evening - I am in the process of trying to call back a list of categories and sub categories using a WHILE LOOP inside of a WHILE LOOP. It works on a different part of the site within the admin panel but not here. Here it only calls one sub category and moves on to the next parent category instead of finishing the loop and pulling all sub categories out... // CATEGORIES $query = "SELECT * FROM cat"; $result = mysql_query($query); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $catid = $row['id']; $catname = $row['name']; $output .= "<li class=\"level0 nav-2 parent\" onmouseover=\"toggleMenu(this,1)\" onmouseout=\"toggleMenu(this,0)\"> <a href=\"product.php?cat=$catid\"> <span>$catname</span> </a>\n"; $querynav = "SELECT * FROM subcat WHERE pid = '$catid'"; $resultnav = mysql_query($querynav); while($array = mysql_fetch_array($resultnav, MYSQL_ASSOC)) { $subcatid = $row['id']; $subcatname = $row['name']; $output .= "<ul class=\"level0\"> <li class=\"level1 nav-2-1 first\"> <a href=\"product.php?cat=$catid&subid=$subcatid\"> <span>$subcatname</span> </a> </li> </ul> </li>"; } } A WHILE loop in a FOR loop problem Script about links and sublinks from 1 table. In fact 2 questions about that. 1) In the FOR loop I have for example to do the loop 3 times. (needs to find 3 results withing the loop with if and else) When first time, he's gonna search within the WHILE loop that holds (for example) 10 records of the DB in a variable. He needs to search for rowid number 5, he found it He goes out of the WHILE loop and goes searching again but now for rowid number 2 Now it seem that the WHILE loop start searching for number 2 but won't start from his first row in the variable (10 rows from the db ). He start at row number 6 instead of beginning all over again !!! -> so the order of the numbers of rows MUST be in an ascending order, ortherwise he won't find them all ! But the numbers I have are NOT in an ascending order !!! Why doesn't the WHILE loop begin again from his row 1 in the variable ? FOR loop { WHILE loop { content here, break; } } 2) even when I get all the result in an ascending order, he won't go doing a second search but with a different rowid number that he gets from the FOR loop. It is giving me back indeed the right new rowid number, but the WHILE loop is doing nothing. I have put many echo "..."; and other stuff for checking but can't find the cause ! Here's the code : Code: [Select] // $ResultShow = 10 rows from mysql db if(isset($ResultShow)){ if (mysql_num_rows($ResultShow) >= 1){ //$linksuborder = "2,3,4"; $array1 = explode(",", $linksuborder); sort($array1); for ($n = 0; $n < count($array1); $n++){ // searchin for the right row id in the variable $ResultShow where we find the numbers for next loop $r1 = each($array1); While($Row2 = mysql_fetch_array($ResultShow)) { if($Row2["linkid"] == $r1['value']) // found it, now look for the numbers that we'll put in an array { echo "---here the content---"; // linksuborder is where numbers from row id's are stored like 5,2,8 //now put them in an array $array2 = explode(",", $Row2["linksuborder"]); sort($array2); for ($n2 = 0; $n2 < count($array2); $n2++){ $r2 = each($array2); ////// here searching for the sublinks ////// While ($Row3 = mysql_fetch_array($ResultShow)) { if($Row3["linkid"] == $r2['value']) // search for the right row id within the variable $ResultShow { echo "---here the content---"; break; // found it, so no need to do the rest of the loop } // end if } //end while ////// end searching for sublinks ////// } // end for } // end if else { echo "--- content here ---"; } } // end while } // end for } //end if } // end if Table : linkid linksuborder linktitle 1 2,3,4 2 9,7,8 mainlink1 3 10 mainlink2 4 mainlink3 5 6 7 sublink3 8 sublink2 9 sublink1 10 sublink4 -> linksuborder 2,3,4 are the row id's for the mainlink -> than we put the numbers 9,8,7 (also row id's) mentioned in row linkid 2 also in a new array -> now we can search for the sublinks -> get the details from row linkid 9, than 7, than 8 -> First mainlink is compleet, now go to row linkid 3 to do it all over again for the next mainlink... RESULTS from an sorted array -> sort($linksuborder); ------------------------------------------------------------- mainlink1 : sublink1, sublink2, sublink3 mainlink2 : **no result back but it should * mainlink 3 : **no result back but it should * I'm having a really bad brain fart and I cannot get the logic correct here lol. I need divs wrapped around every set of 5 images so if there is a total of 8 images then there would be 2 sets of divs (first with 5 images, second with 3 images) and if there was 12 images then there would be 3 sets of divs (first two with five images, last one with 2 images) etc etc What am I doing wrong and is there an easier way to do this? http://pastebin.com/QfsFxe4G Thanks! 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(); }?> So I have a PHP parent page that is accesses that scans the database for the passed token in the URL and then replaces content on the template page using a loop. My issue is that I am trying to use a loop on the secondary page which causes the white screen of death. From what I can tell the loop inside a loop is causing the issue. I'll paste the code below, let a newbie know if you have any ideas or can point me in the right direction. Thanks everyone! Here is the chunk of code from the parent page with the loop function.... // output pre content eval("\$preContent = \"$preContent\";"); print_r( replaceChar($preContent) ); $sqlSearch = "SELECT * FROM ".$row[tdbd_name]." WHERE ".$sqlKeyword." LIMIT ".MAX_ROWS; $resultSearch = mysql_query($sqlSearch); while($displayrows = mysql_fetch_assoc($resultSearch)) { $display = replaceTokens($loopTemplate); $display = str_replace('\\', '[backslash]', $display); $display = str_replace('[%', '$displayrows[', $display); $display = addslashes(str_replace('%]', ']', $display)); $display = replaceTokens($display); $display = changeCase($display); eval("\$display = \"$display\";"); $display = stripslashes($display); $display = str_replace('[backslash]', '\\', $display); $display = replaceChar($display); print_r( $display ); } // output post content And here is the loop function from the page that the above code loops through replacing tokens in. <?php $mySQLServer = "xxxxxxxxx"; $mySQLUser = "xxxxxxxxxx"; $mySQLPass = "xxxxxxxx"; $mySQLDB = "xxxxxxxxxxxxx"; $SQLToday = date("m/d/y") . "<br />"; $SQLsevendays = mktime(0,0,0,date("n"),date("j")-7,date("Y")); $SQLsevenname = (date("l", $SQLsevendays)); $SQLsevennumber = (date("jS", $SQLsevendays)); $dbhandle = mssql_connect($mySQLServer, $mySQLUser, $mySQLPass) or die("Couldn't connect to SQL Server on $myServer"); $selected = mssql_select_db($mySQLDB, $dbhandle) or die("Couldn't open database $myDB"); $query = "WEB_ApproveHistory @State='CA', @Days=5, @Records=8"; $data = mssql_query($query); $result = array(); while ($row = mssql_fetch_object($data)) { $result[] = $row; $returnedresults = (97*($row->TotalApprovals)) ; } $englishreturnedresults = number_format($returnedresults); echo 'In just the last week since ' . $SQLsevenname . ' the ' . $SQLsevennumber . ' has delivered '; echo $englishreturnedresults; echo ' Here are just a few people '; echo '<ul class="BulletCheck">'; mssql_next_result($data); while ($row = mssql_fetch_object($data)) { $result[] = $row; echo '<li>' . ' ' . $row->FirstName . ' From '. $row->City . ', ' . $row->State .' PreApproved On ' .$row->ApprovedDate . '</li>'; } mssql_close($dbhandle); ?> Hi.. I have while loop inside while loop but I encountered problem in displaying data inside while loop or the second while loop. here is my code: Code: [Select] <?php error_reporting(0); $con = mysql_connect('localhost', 'root',''); if (!$con) { echo 'failed'; die(); } mysql_select_db("mes", $con); ?> <script type="text/javascript"> function showDetails(pcode) { var clickElement = pcode.value; var click_id = pcode.id; // var value_ = document.getElementById(click_id).checked // = document.getElementById(clickElement).checked; //var Table = (document.getElementsByName('list')[0].value); var Table = document.getElementById('kanban_list'); var rows = Table.rows; var strSelect = document.getElementById(click_id).value; //alert(strSelect) for (var i = 0; i < rows.length; i++) { var row = rows[i]; //row.style.display = (row.id.substr(0,3) == strSelect) ? 'none' : ''; //row.style.display = (row.id.substr(0,3) == strSelect) ? // row.style.display = 'none'; // row.style.display = ''; if (row.id.substr(0,3) == strSelect) { row.style.display = ((document.getElementById(click_id).checked) == false) ? 'none' : '' } //(document.getElementById(click_id).checked == false) ? 'none' : '' : ''; } } </script> <?php $sql = "SELECT kc.PCODE, kc.count_wip_chemical_weighing, kc.count_wip_compounding, kc.count_wip_extrusion, kc.count_wip_forming, kc.count_wip_deflashing, kc.kanban, kc.virtual, p.max_lot, p.min_lot FROM kanban_checker kc JOIN plan p ON kc.PCODE = p.PCODE ORDER BY p.PCODE"; $result = mysql_query($sql, $con); ?><label>Display Details:</label><input onclick='showDetails(this);' id='chkDetail' type='checkbox' checked='checked' value='wip'/> <?php echo "<table id='kanban_list'>"; echo "<tr> <th> PCODE </th> <th> LOT CODE </th> <th> CHEMICAL WEIGHING </th> <th> COMPOUNDING </th> <th> EXTRUSION </th> <th> FORMING </th> <th> DEFLASHING </th> <th> KANBAN </th> <th> VIRTUAL </th> <th> MAX LOT </th> <th> MIN LOT </th> </tr>"; while($row = mysql_fetch_assoc($result)){ echo "<tr> <td>$row[PCODE]</td> <td> </td> <!-- <td>$row[LOT_CODE]</td> --> <td>$row[count_wip_chemical_weighing]</td> <td>$row[count_wip_compounding]</td> <td>$row[count_wip_extrusion]</td> <td>$row[count_wip_forming]</td> <td>$row[count_wip_deflashing]</td> <td>$row[kanban]</td> <td>$row[virtual]</td> <td>$row[max_lot]</td> <td>$row[min_lot]</td> </tr>"; $sql = "SELECT kd.LOT_CODE, kd.wip_chemicalweighing, kd.wip_compounding, kd.wip_extrusion, kd.wip_forming, kd.wip_deflashing FROM kanban_data kd JOIN plan p ON kd.PCODE = p.PCODE ORDER BY p.PCODE "; $result_kanban_data = mysql_query($sql, $con); while($row_data = mysql_fetch_assoc($result_kanban_data)){ echo "<tr id='wip'> <td></td> <td> $row_data[LOT_CODE]</td> <td> $row_data[wip_chemicalweighing]</td> <td> $row_data[wip_compounding]</td> <td> $row_data[wip_extrusion]</td> <td> $row_data[wip_forming]</td> <td> $row_data[wip_deflashing]</td> </tr>"; } } echo "</table>"; ?> I attach the image of result from this code But the output that I want is all LOT_CODE with P35 PCODE will only display below P35 and all LOTCODE with P35M PCODE will only display below P35M. Thank you I hope somebody can help me.. Hi, I am new to PHP. Can someone explain me clearly how to use while loop inside while loop to print "*" in square shape. Thank you for your help. |