Jump to content

Search the Community

Showing results for tags 'loops'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

Found 14 results

  1. Hi, Freaks, I hope all are well. I'm trying to make a while loop and there's a common manner used that I've seen in many, many example of code -> <?php while($row = mysqli_fetch_array($data_query)) { ... } and this manner of doing it auto-stops when it's to the end of the mysqli array. Using this exact way is not compatible with the syntax that I can use as I use a database wrapper that is highly abstracted. for example, this would be the typical layout of a DB query for a user post -> <?php $table = "un_posts"; $field = "deleted"; $value = "no"; $rule = "ORDER BY id DESC"; $query = $this->_db->get($table, array($field, "=", $value), $rule); $this->_data = $query->all(); // $this->_data is an array of objects and this would be my typical way of assigning the data -> <?php foreach ($this->data() as $obj) { $post_data = array( "id" => $obj->id, "content" => $obj->content, "added_by" => $obj->add_by, "date_added" => date("F d, Y H:i:s", strtotime($obj->date_added)), "user_to" => $obj->user_to, ); for project specific reasons I'd like to change this from a foreach loop to a while loop. What I found out is that the auto-stop of the while loop using the $row = mysqli..... does not work if I do something like this -> <?php while($obj = $this->data()) { $post_data = array( "id" => $obj->id, "content" => $obj->content, "added_by" => $obj->add_by, "date_added" => date("F d, 20y H:i:s", strtotime($obj->date_added)), "user_to" => $obj->user_to, ); and it creates an infinite loop. Keeping in mind that $this->data() (I have a class method data() that returns $this->_data if anyone noticed the difference) is an array of objects why am I not getting the same result as <?php while($row = mysqli_fetch_array($data_query)) { ... } I don't understand. They're both arrays being looped through. What's the difference where mine isn't breaking the loop at the end but the mysqli array breaks the loop at the end of it?
  2. Hi Freaks, the weekend is upon us again. I wish you all well. I have an issue I've been working on today and have hit a mental roadblock. Hoping someone with the time and will will talk me through it. I'm creating a table while looping through an API array and I've hit a couple snags. Here is the repeated HTML -> $html = " <tr class='mt-2'> <td>{$rank}.</td> <td><img src='{$image}' height='75' width='75'></td> <td>{$name}</td> <td class='bold'>\${$final_worth}B</td> <td class='{$class}'>\${$last_change}</td> <td>{$country}</td> <td>{$source}</td> <td><button class='bg-color-primary text-color-third px-2' id='more_btn' onclick='showDetails({$cnt})'>More</button></td> </tr> <tr > <div id='details'>lorem fucking ipsum wahoo baby</div> </tr> "; Everything was going as expected until I went to add the second row (div#details). There's actually 2 issues at play here - the first is how I make each button/div#details connected so button1 only effects div1 etc. I can't tackle that one yet though, because right now when any button is clicked div#details shows up above the table header rather than underneath the previous row. So until I have the positioning correct I can't really tackle the js functionality. Can someone please tell me why the <tr><div#details> is not appearing underneath it's previous row? The js code is as follows -> <script> var cnt = <?php echo $cnt; ?>; function showDetails(cnt) { var details = "details"; var x = document.getElementById(details); if (x.style.display === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } </script> I know the code is a mess right now. It's kind of shameful lol but like I said I can't really do more with it until I can figure out why that table row isn't positioning properly
  3. I've made this code for a very simple registration form practice: //assign form variables $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $username = $_POST['username']; function clean_names($dirty_name) { strip_tags($dirty_name); str_replace(' ', '', $dirty_name); ucfirst(strtolower($dirty_name)); //return $dirty_name; } $names = array($firstname, $lastname, $username); if(isset($_POST['register_button'])) { // WHY IS THIS FUNC CALL NOT WORKING?? foreach($names as $name) { clean_names($name); } echo "First Name: " . $firstname . "<br>"; echo "Last Name: " . $lastname . "<br>"; echo "Username: " . $username . "<br>"; } The values are returned but they haven't been put through the clean_names function. I'm really new with PHP. Can someone tell me why this isn't working? Thank you
  4. So I have a database that is structured like this: https://imgur.com/a/DdyTqiE Sample data: https://imgur.com/a/kYwmuO1 For each appointment, a student can have multiple categories, such as 'Academic Probation, Re-Admit' etc... I would like to loop through this table, and get a count of how many were 'is_no_show' and 'is_cancelled' per (unique) category with respect to 'scheduled_student_services.' For example, in the sample data, we see that the first appointment has 4 categories (Academic Probation, Entering Cohort Year 20051, First Generation, and Re-Admit'). Now one of these categories - Academic Probation matches up with what they were scheduled for - '1st Term Probation Advising'. And they cancelled this appointment, so we want the count of cancellations under Academic Probation to go up by 1. How would I approach this? I know I probably need to do two loops but I'm not sure the PHP syntax for this. Any suggestions or tips would be helpful. Thank you for your time!
  5. I am building an e-commerce site and I am aiming to create a front end displaying my products with an option for customers to buy them, and have a content management system as a back end for an admin to edit product information. Currently I am storing information about my products on a mysql database. I access and display the product info using a while loop. Below is a simplified version of what I am doing without any html to style it. This code will go through the database and each iteration will go the to the next row and display the info about the next product. $query = mysql_query("SELECT * FROM truffleProducts"); while ($row = mysql_fetch_array($query)) { $id = $row['id']; $name = $row{'Name'}; $price = $row{'Price'}; $desc = $row{'Description'}; echo $id; echo $name; echo $price; echo $desc; } I have began to implement a 'buy' button so that customers are able to click on a button next to the product info and purchase it. However I have come across a problem which is where my program won't be able to tell which product you have selected as the number stored in the $id variable will just be the last product it has fetched from the database. I can't differentiate between all the product's buy buttons, so it will impossible to place an order for a customer with the current system I have. Can any one tell me how to get the id number of the specific product that a user has selected? I only started learning PHP a month or two ago so assume I know nothing
  6. Hi all, I have a looping error in my PHP. I am trying to add use a while statement to gather the users first and last name in to a string, add them to an array called $friendname, then check that the $friendname[] is only output/echoed once. At the moment the code looks good to me but with multiple rows with the same name associated, the name is echoed the same amount of times as rows, instead of once as it is supposed to be. Any ideas anyone? while($row2 = mysqli_fetch_assoc($result2)) { $friendcode = $row2['Code']; $names = "SELECT FirstName, LastName from users WHERE Code = '$friendcode' AND Code != '$crewcode'"; $resultnames = mysqli_query($cxn,$names) or die ("Can't get friends names."); while($rownames = mysqli_fetch_assoc($resultnames)) { $friendname = array(); $newfriendname = ($rownames['FirstName'].' '.$rownames['LastName']); if (!in_array($newfriendname, $friendname)) { array_push($friendname, "$newfriendname"); echo $newfriendname; } } }
  7. Hi there i have recently started working with php so I will probably be a familiar name around here. I have been giving a task that I have got a bit stuck with. To give a brief overview I have products that are stocked in x number of warehouses, when a customer places an order depending on their location I will ship from the warehouse that is closest to them if it has all products in stock. I have the following two arrays The first represents a customers order containing the id of the product and the quantity they have selected. e.g. product id:35659, qty:1 Array ( [35659] => 1 [35699] => 1 [35734] => 2 ) The second array shows the quantity in stock for each product in each 3 warehouses that stock it e.g. 35659 being the product id, [9][114][126] being the warehouse and 10,1,0 being the quantity of stock for that item in the warehouse. Array ( [35659] => Array ( [9] => 10 [114] => 1 [126] => 0 ) [35699] => Array ( [9] => 8 [114] => 0 [126] => 5 ) [35734] => Array ( [9] => 10 [114] => 0 [126] => 0 ) ) function check_warehouse_stock($order=array(), $stock=array(), $warehouse=0) { foreach($order as $id => $qty) if($stock[$id][$warehouse] < $qty) return false; return true; } // $warehouses is an array of my warehouses already in their preference order foreach($warehouses as $w) { if(check_warehouse_stock($order, $stock, $w)) break; $w = false; } // $w is now the first warehouse with all the stock, or false if no warehouses have any stock So far I have got the above code which loops through each warehouse and goes into a function that checks each item in their order and sees if any item in their basket is below the quantity in the warehouse, if no items is below the quantity it returns true and that is the first warehouse with all items in stock, if no warehouse has all items in stock it returns false. This is where I am getting stuck, if no warehouse has all items in stock I need to go into a similar function and have some sort of rule that checks if no one warehouse has all products in stock I will ship from wherever has each product in stock starting with the closest and so on... e.g. if the first warehouse had 2 of the 3 items in stock and the second warehouse had 1 in stock we would ship 2 products from the first and 1 from the second. Any help would be greatly appreciated, even with just the logic on how to approach this. Thanks
  8. I'm a beginner currently going through php loops. I pretty much understand the fundamentals of loops but i can't figure out why this piece of code. <?php $count = 0; while ( true ) { $count++; echo "I ’ ve counted to: $count <br />"; if ( $count == 10 ) break; } ?> results in this output: I ’ ve counted to: 1 I ’ ve counted to: 2 I ’ ve counted to: 3 I ’ ve counted to: 4 I ’ ve counted to: 5 I ’ ve counted to: 6 I ’ ve counted to: 7 I ’ ve counted to: 8 I ’ ve counted to: 9 I ’ ve counted to: 10 If a loop goes back to the starting point after successful completion, why isn't the value of the variable $count equal to 1 each time, thereby outputting "I've counted to: 1 over and over.
  9. I have a query which is looking for events on any given month of the year. It looks as follows... $events = array();mysql_select_db($database_dbconnect, $dbconnect);$query = "SELECT calsect, title,idcalendar, DATE_FORMAT(event_date,'%Y-%m-%d') AS event_date FROM calendar WHERE event_date LIKE '$year-$month%'";$result = mysql_query($query, $dbconnect) or die(mysql_error()); while($row = mysql_fetch_assoc($result)) {$events[$row['event_date']][] = $row;} I then have a function which calls a calendar. As the function is looping through days of the week it also checks on each day if there is any event. If there is it prints it. If not it moves on to the next day. It actually works great. I can echo the title, idcalendar and the event_date but I can not the calsect field. /* print "blank" days until the first of the current week */for($x = 0; $x < $running_day; $x++):$calendar.= '<td class="calendar-day-np"> </td>';$days_in_this_week++;endfor; /* keep going with days.... */for($list_day = 1; $list_day <= $days_in_month; $list_day++):$calendar.= '<td class="calendar-day"><div style="position:relative;height:100px;">';/* add in the day number */$calendar.= '<div class="day-number">'.$list_day.'</div>'; $event_day = sprintf('%04d-%02d-%02d', $year, $month, $list_day); /* list the events */if(isset($events[$event_day])) {foreach($events[$event_day] as $event) { //My title appears but the $event['calsect'] is not!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! $calendar.='<div class="' .$event['calsect']. '">' .$event['title']. '</div>';}}else {$calendar.= str_repeat('<p> </p>',2);} If I view source on an event I get this. <div class="">Test Event</div> where class should equal $event['calsect'] (or blue in this case) .
  10. I have an array with data that looks like this: 01 | organization_1 | email_A | publication_A1 | pubID_A1 02 | organization_1 | email_A | publication_A2 | pubID_A2 03 | organization_1 | email_A | publication_A3 | pubID_A3 04 | organization_2 | email_B | publication_B1 | pubID_B1 05 | organization_2 | email_B | publication_B2 | pubID_B2 06 | organization_3 | email_C | publication_C1 | pubID_C1 07 | organization_4 | email_D | publication_D1 | pubID_D1 08 | organization_4 | email_D | publication_D2 | pubID_D2 The array is structured like this: array('org' => organization_x, 'email' => email_x, 'title' => publication_x, 'pub_id' => pubID_x) What I need to do is output this array so that it displays as individual email messages with a submit button after each. A person viewing this page would review the displayed message and he or she would have the option to click submit to send a particular message to the appropriate email. Here's the initial display I need to create: <!-- Message #1 --> <form> <input type="hidden" name="pub_ids" value="pubID_A1;pubID_A2;pubID_A3"> <input type="hidden" name="recipient" value="email_A"> <input type="hidden" name="organization" value="organization_1"> <!-- start on-screen text display --> To: email_A Your account contains the following publication titles: * publication_A1 * publication_A2 * publication_A3 You can edit these publications after logging into our system. Your email address, email_A, serves as your username. Thanks! <!-- end on-screen text display --> <input type="submit" name="submit" value="submit"> </form> <!-- Message #2 --> <form> <input type="hidden" name="pub_ids" value="pubID_B1;pubID_B2"> <input type="hidden" name="recipient" value="email_B"> <input type="hidden" name="organization" value="organization_2"> <!-- start on-screen text display --> To: email_B Your account contains the following publications: * publication_B1 * publication_B2 You can edit these publications after logging into our system. Your email address, email_B, serves as your username. Thanks! <!-- end on-screen text display --> <input type="submit" name="submit" value="submit"> </form> ...and on until all of the items in the array have been processed. I've tried some version of the following code for too long now. The idea is to loop through each item, concatenating the pub_id and title data into text strings to be passed through the form or shown on screen as needed. When the script hits a new organization name, it should put all the pieces together and then get started on the next organizaton's email message. The Code: $current_org = ''; $pub_ids = ''; $titles = ''; foreach ($array AS $value) { $pub_ids .= $value['pub_id'] . ';'; $titles .= '* ' . $value['title'] . '<br />'; if ($current_org != $value['org']) { echo '<form>'; echo '<input type="hidden" name="pub_ids" value="' . $pub_ids . '">'; echo '<input type="hidden" name="recipient" value="' . $value['email'] . '">'; echo '<input type="hidden" name="organization" value="' . $value['org'] . '">'; echo 'To: ' . $value['email']; echo '<br /><br />'; echo 'Your account contains the following publication titles:'; echo '<blockquote>'; echo $titles; echo '</blockquote>'; echo 'You can edit these publications after logging into our system. Your email address, ' . $value['email'] . ', serves as your username.'; echo '<br /><br />'; echo 'Thanks!'; echo '<input type="submit" name="submit" value="submit">'; echo '</form>'; echo '<br /><br />'; $pub_ids = ''; $titles = ''; $current_org = $value['org']; } } The Problem: The problem seems to be the first organization with more than one publication only gets one publication listed out. Then the next organization gets the last org's publication listed as well as their own. Then the rest are thrown off. Thinking this has something to do with my "if ($current_org != $value['org'])". Since $current_org starts off as NULL the first loop will never be set to $value['org'], so I get one loop through that gives me a pub_id, a title, and an email message -- then the old_org "changes" from NULL to the first $value['org'] value and the loop starts over again. I think this is what is going on. I can't figure out how to fix this though. Where/how would I check to see if the org value has changed? Any insight into this problem is much appreciated!
  11. So I'm trying to write a script that will reset some values in a Magento product database, but I'm having some issues. I need to code to run for all products, in all stores, for all th attributes. I wrote the inital little script, and it works fine: $product_id = 1657; $store_id = 4; $attr = 'name'; $product = Mage::getModel('catalog/product') ->load($product_id) ->setStoreId($store_id) ->setData($attr, false) ->save(); The issue is, I need it to run for all products, all stores, all attributes. My next step was to test it with one attribute, one store, all products, and my code was: $product_ids = Mage::getModel('catalog/product')->getCollection()->getAllIds(); $store_id = 4; $attr = 'name'; foreach ($product_ids as $product_id){ $product = Mage::getModel('catalog/product') ->load($product_id) ->setStoreId($store_id) ->setData($attr, false) ->save(); } That code gets me no results. If I run the foreach loop and print_r the $product_ids the array contains what I think it should. Anyone have any ideas? I haven't even started to touch the multiple attributes in multiple stores since this doesn't work yet.
  12. Hello, I am trying to do a while loop and the loop does fine because I tested it using an echo statement. However, Every time I remove the echo statement and place a MySQL Alter in there, it does not work. $d = 1; while ($d <= $depth) { $w = 1; while ($w <= $width) { mysql_query("ALTER TABLE `$b` ADD `test$b$w$d` int unsigned not null"); $w++; } $d++; } But.... When I use the same Alter Phrase outside the loop it works fine. What am I missing here? I do not understand why this will not work in the loop but does outside of it! Thanks for your help!
  13. I have a table that I want to create into a horizontal menu using lists/CSS in my header. I have the code that creates the menu, I just can't figure out the foreach loops to actually generate the menu. $refs = array(); $list = array(); $result = full_query("SELECT id,title,slug,parent FROM `page`"); while($data = mysql_fetch_assoc($result)) { $thisref = &$refs[$data['id']]; $thisref['parent'] = $data['parent']; $thisref['title'] = unserialize($data['title']); $thisref['slug'] = $data['slug']; if($data['parent'] == 0) { $list[$data['id']] = &$thisref; } else { $refs[$data['parent']]['children'][$data['id']] = &$thisref; } } // can't figure this part out foreach($list as $keys => $var) { foreach($var as $vkey => $vvar) { if(isset($vkey['children'])) { print $vkey; } } } Which, with my current data, results in this array: Array ( [4] => Array ( [children] => Array ( [1] => Array ( [parent] => 4 [title] => Child1 [id] => 1 [slug] => child1 ) ) [parent] => [title] => Parent1 [id] => 4 [slug] => parent1 ) [6] => Array ( [children] => Array ( [2] => Array ( [parent] => 6 [title] => child2 [id] => 2 [slug] => child2 ) [3] => Array ( [parent] => 6 [title] => child3 [id] => 3 [slug] => child3 ) [8] => Array ( [parent] => 6 [title] => child4 [id] => 8 [slug] => child4 ) ) [parent] => [title] => Parent2 [id] => 6 [slug] => parent2 ) [7] => Array ( [parent] => [title] => Parent3 [id] => 7 [slug] => parent3 ) [9] => Array ( [parent] => [title] => Parent4 [id] => 9 [slug] => parent4 ) ) Am trying to get the foreach to do this: Parent1 Child1 Parent2 Child2 Child3 Child4 Parent3 Parent4 But horizontally. Any help is greatly appreciated!
  14. Hi I am currenly doing a project where i am required to send some values to secure http via post request..I am using Curl for this and that works fine, what I am stuck on is how to retrieve stored database values and send each one individually in a loop to the specified url in the curl script. Hard to explain but heres an example: e.g I have a number of reports in db (123456, 123654, 456321) and each one will retrieve a report from the url as they are the specified report_ids required. I would like to pull each one from the database using a foreach loop assigning the report number to $reportid variable one at a time, and also when the report is retrieved with each one, fwrite it to file. I can currently get all of the above working but only if i assign the report number in the script rather than assigning it the db value and looping through each one. I suppose my question is how can i not only loop through db values but assign each id to the reportid sent via curl and then do it all over again for the next id... Any help in the right direction would be awesome.!
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.