Jump to content

Search the Community

Showing results for tags 'loop'.

  • 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

  1. I have 3 staff members that need to pick vacation in a certain order. Each have X weeks vacation and can pick off a calendar their choice 1-3 weeks per round. I'm trying to loop through the DB to find who is next to pick with weeks left ~~~~~~First round of picking~~~~~~ STAFF 1 - PICK ORDER 1 - 3 weeks available STAFF 2 - PICK ORDER 2 - 5 weeks available STAFF 3 - PICK ORDER 3 - 3 weeks available Staff 1 takes 2 Weeks Staff 2 takes 1 Weeks Staff 3 takes 3 Weeks ~~~~~~Second round of picking~~~~~~ STAFF 1 - PICK ORDER 1 - 1 weeks available STAFF 2 - PICK ORDER 2 - 4 weeks available STAFF 3 - PICK ORDER 3 - No weeks left Staff 1 takes 1 Weeks Staff 2 takes 3 Weeks Staff 3 Skipped ~~~~~~Third round of picking~~~~~~ STAFF 1 - PICK ORDER 1 - No weeks left STAFF 2 - PICK ORDER 2 - 1 weeks available STAFF 3 - PICK ORDER 3 - No weeks left Staff 1 Skipped Staff 2 takes 1 Weeks Staff 3 Skipped ~~~~~~~~~~~~ All staff 0 weeks left end --calendar.php-- $year=2020; $sql = "SELECT * FROM vac_admin WHERE pick_year='$year'; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { $row_admin = mysqli_fetch_assoc($result); } $current_pick_staff = $row_admin['current_pick_staff']; $sql = "SELECT * FROM vac_pick_order WHERE pick_year='$year' && pick_order = '$current_pick_staff'"; $result = mysqli_query($conn, $sql); $row = mysqli_fetch_assoc($result); if($row['vac_c_counter'] < 0){ $emp_num = $row['emp_num']; }ELSE{ ?????????????????? goto next staff with weeks > 0 ?????Somthing like if ($current_pick_staff == 3){ $current_pick_staff = 1; }ELSE{ $current_pick_staff++; } ?????????????????? } ~<FORM>~~~~~~~~~~~~~~~~~~~~~ Staff with $emp_num can now pick ~~~~~~ $_POST -> $date = XXXX-XX-XX; $num_weeks = X; $emp_num; ~</FORM>~~~~~~~~~~~~~~~~~~~~~ --process.php-- $year = 2020; $date = $_POST['date']; $num_weeks = $_POST['num_weeks']; $emp_num = $_POST['emp_num']; $sql = "INSERT INTO vac_picks (pick_year,emp_num,date) VALUES ($year,$emp_num,$date)"; $sql = "UPDATE vac_pick_order SET vac_c_counter=vac_c_counter - $num_weeks WHERE emp_num='$emp_num'; $sql = "UPDATE vac_admin SET pick_order=pick_order +1 WHERE pick_year='$year' ; Then back to calendar.php until all weeks gone.
  2. I have a foreach loop that returns 5 users. I basically want to show only 1 of the 5 users. Every time that loop is run, it should show a random user of the 5, as oppose to the same user every single time. How can that be done? This is my query so far. $find_user = $db->prepare("SELECT user_id FROM users ORDER BY user_id ASC"); $find_user->execute(); $result_user = $find_user->fetchAll(PDO::FETCH_ASSOC); if(count($result_user) > 0) { foreach($result_user as $row) { $user_id = trim($row['user_id']); var_dump($user_id); } }
  3. StuHannah

    Loop

    Hi, I want to create a loop within PHP and MySQL. At the moment my table has a column named active that is either 0 or 1 to represent active or not. I want to update my current loop. I know that there are 5 days we operate (at the moment) so I want to pull through the table using a variable so that I can loop through and select days that are active and for the days that are not active simply print a greyed out row. Can anyone point me in the right direction, I was thinking a whileloop so for example: // $i is the days we are active) while ($i = 1, $i <= 5, $i++) { echo "Day name"; // If the day is active then print the name } ​else if the day isn't active it will still be printed, but greyyed out. This is my current query: $query = "SELECT * FROM tbl_days WHERE Active = 1"; $result = mysqli_query($dblink, $query);if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { echo "<tr>"; echo "<td>" . $row["ID"] ."</td>"; echo "<td>" . $row["DayName"] . "</td>"; echo "<td>" . $row["Active"]. "</td>"; echo "</tr>"; } } else { echo "Nothing active on the system at the moment."; } Thanks in advance, and hope i've given enough information. S
  4. Say I have the following. record_id | record_name ----------------------------------- 1 one 2 two 3 three 3 three 3 three 4 four 5 five 5 five I want to search through through the table and find all the records. If there are multiple records with same id, I want to combine them into 1 variable and use that. So in the above example, I have 3 threes and 2 fives. I want to combine them so that I only get 1 three and 1 five. How can that be done? A normal query looks like this. $get_records = $db->prepare("SELECT * FROM records"); $get_records->execute(); $result_records = $get_records->fetchAll(PDO::FETCH_ASSOC); if(count($result_records) > 0) { foreach($result_records as $row) { $record_id = $row['record_id']; $record_name = $row['record_name']; } }
  5. Say I have a records table with multiple records. There could be multiple records with the same name but different amounts. For Eg. Looking at the table below, the results should retrieve newest record-1 and record-2 because their amount is equals to or greater than 5.00. Record-3 is not selected because it falls below 3.00. record_id record_name record_amount 1 record-1 4.00 2 record-1 3.00 3 record-2 2.00 4 record-1 5.00 5 record-2 6.00 6 record-3 3.00 $get_records = $db->prepare("SELECT record_id, record_name FROM records WHERE record_amount >= :record_amount ORDER BY record_id DESC"); $get_records->bindValue(':record_amount', 5.00); $get_records->execute(); $result_records = $get_records->fetchAll(PDO::FETCH_ASSOC); if(count($result_records) > 0) { foreach($result_records as row) { $record_id = $row['record_id']; $record_name = $row['record_name']; echo $record_name; } } Currently the query above outputs ALL the rows that matches the >=. What I want to do is select only ONE row of each unique record name that matches the criteria. And that row is typically the last row that was inserted. So the output would be like only these two. How do I do that? 4 record-1 5.00 5 record-2 6.00
  6. Note: This site is only local and used as a calculator, so to speak, and I have no concerns about data structures or injection at this time, merely the formula in this loop. I have a working php loop involving an html table that houses test values. I am attaching a screenshot of the table, but it pulls data from a database table for 4 test attributes per 8 tests. In other words, there are 8 test columns and each column is filled with 4 test variables from the database. The 5th row calculates a percentage from a formula and after all of this is done for the 8 tests, there is an overall percentage of the 8 average values. This makes more sense looking at the screenshot, but the final row is made up from the formula. This works perfectly, except the new files we're using can have less than 8 tests, so my old formula basing the answer off of 8 tests is inaccurate now. I'm looking for a fairly quick and dirty solution for the time being that will just count how many columns actually contain data. Here is the code for the table, and the php loop data is near the bottom. Basically, I want a better way to use a count in my form loop as well as my average where they are currently using 8. <table style="width:100%; border:none; border-collapse:collapse;"> <tr style="border:none;"> <th style="border:none; text-align: left;" >Meter Test</th> <th style="border:none;">Test 1</th> <th style="border:none;">Test 2</th> <th style="border:none;">Test 3</th> <th style="border:none;">Test 4</th> <th style="border:none;">Test 5</th> <th style="border:none;">Test 6</th> <th style="border:none;">Test 7</th> <th style="border:none;">Test 8</th> </tr> <tr style="border: none;" > <td style="border:none; text-align: left;">Test Rate GPM: </td> <td><? echo $row['test1TestRateGPM'];?> </td> <td><? echo $row['test2TestRateGPM'];?> </td> <td><? echo $row['test3TestRateGPM'];?> </td> <td><? echo $row['test4TestRateGPM'];?> </td> <td><? echo $row['test5TestRateGPM'];?> </td> <td><? echo $row['test6TestRateGPM'];?> </td> <td><? echo $row['test7TestRateGPM'];?> </td> <td><? echo $row['test8TestRateGPM'];?> </td> </tr> <tr> <td style="border:none; text-align: left;">Meter Volume: </td> <td><? echo $row['test1MeterVol'];?> </td> <td><? echo $row['test2MeterVol'];?> </td> <td><? echo $row['test3MeterVol'];?> </td> <td><? echo $row['test4MeterVol'];?> </td> <td><? echo $row['test5MeterVol'];?> </td> <td><? echo $row['test6MeterVol'];?> </td> <td><? echo $row['test7MeterVol'];?> </td> <td><? echo $row['test8MeterVol'];?> </td> </tr> <tr> <td style="border:none; text-align: left;">Tester Volume: </td> <td><? echo $row['test1TesterVol'];?> </td> <td><? echo $row['test2TesterVol'];?> </td> <td><? echo $row['test3TesterVol'];?> </td> <td><? echo $row['test4TesterVol'];?> </td> <td><? echo $row['test5TesterVol'];?> </td> <td><? echo $row['test6TesterVol'];?> </td> <td><? echo $row['test7TesterVol'];?> </td> <td><? echo $row['test8TesterVol'];?> </td> </tr> <tr> <td style="border:none; text-align: left;">Tester Accuracy: </td> <td><? echo $row['test1Accuracy'];?>% </td> <td><? echo $row['test2Accuracy'];?>% </td> <td><? echo $row['test3Accuracy'];?>% </td> <td><? echo $row['test4Accuracy'];?>% </td> <td><? echo $row['test5Accuracy'];?>% </td> <td><? echo $row['test6Accuracy'];?>% </td> <td><? echo $row['test7Accuracy'];?>% </td> <td><? echo $row['test8Accuracy'];?>% </td> <td style="border:none;">Overall</td> </tr> <tr> <td style="border:none; text-align: left;">Corrected Accuracy: </td> //here starts the loop within the table cell <?php $sum=0; for($i=1; $i<=8; $i++){ if($row["test".$i."TesterVol"] == 0){ $row["test".$i."TesterVol"] = 0.001; } $testFormA = $row["test".$i."MeterVol"] / $row["test".$i."TesterVol"]; $testFormB = $testFormA * $row["test".$i."Accuracy"]; $testFinalForm = $testFormB; $sum += $testFinalForm; ?> <td><?php echo round($testFinalForm,3) ?>%</td> <?php } $average = $sum / 8; ?> <td><?php echo round($average,5)?>% </td> </tr> </table>
  7. This is the code from my previous topic. It was for getting 3 countdown counters to work on the same page. It does that. But I didn't notice this up until now. It gives me this error and it keeps counting up the errors in firebug. TypeError: document.getElementById(...) is null This is the code. Can you tell me what's wrong with it? <script> $( document ).ready(function() { //Create object with the list of due dates //The 'name' will correspond to the field ID to populate the results var dueDates = { 'date1':'<?php echo $global_payment_due_1; ?>', 'date2':'<?php echo $global_payment_due_2; ?>', 'date3':'<?php echo $global_payment_due_3; ?>' }; var timer = setInterval(function() { //Instantiate variables var dueDate, distance, days, hours, minutes, seconds, output; //Set flag to repeat function var repeat = false; // Get todays date and time var now = new Date().getTime(); //Iterate through the due dates for (var dueDateId in dueDates) { //Get the due date for this record dueDate = new Date(dueDates[dueDateId]); // Find the distance between now an the due date distance = dueDate - now; // Time calculations for days, hours, minutes and seconds days = Math.floor(distance / (1000 * 60 * 60 * 24)); hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); seconds = Math.floor((distance % (1000 * 60)) / 1000); //Determine the output and populate the corresponding field output = "OVERDUE"; if (distance > 0) { output = days + "d " + hours + "h " + minutes + "m " + seconds + "s"; repeat = true; //If any record is not expired, set flag to repeat } document.getElementById(dueDateId).innerHTML = output; //If flag to repeat is false, clear event if(!repeat) { clearInterval(timer); } } }, 1000); }); </script>
  8. I have this code which works as expected: foreach($bidders as $val) { $losing_bidder = ($val->email); echo $losing_bidder; } Let us assume the output is: Bob@email.com Joe@email.com Cindy@email.com Willis@email.com I need to have the loop always ignore (or not echo, or not process) the last value in the array. What adjustment to the code would accommodate that?? Thanks much!
  9. I have a questions table and feedback table. I able to foreach the question header but not the feedback. My code as above: <?php $sql2 = "SELECT DISTINCT[question_id],[q_text] FROM [question]"; $ques = array(); $stmt2 = sqlsrv_query($conn, $sql2, $ques); while ($row = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC)) { $ques[$row['question_id']] = $row['q_text']; } $sql = "SELECT [question_id], [Expr3],[Expr2] FROM [feedback] ORDER BY [Expr2] ASC"; $data = array(); $stmt = sqlsrv_query($conn, $sql); while (list($qid, $a, $eid) = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)) { if (!isset($data[$qid][$eid])) { $data[$qid][$eid] = $newArray2; } $data[$qid][$eid][] = $a; } ?> <div class="container"> <?php // produce table header echo "<table border='1' id='table2excel'>\n"; echo "<tr><th>Employee ID</th>"; // loop over array of questions for the header foreach ($ques as $question) { echo "<th>$question</th>"; } echo "</tr>\n"; foreach ($data as $qid => $question) { foreach ($question as $question => $replies) { echo "<tr><td>$question</td>"; foreach (array_keys($ques) as $q_id) { echo "<td>"; echo $replies[$q_id]; echo "</td>"; } echo "</tr>\n"; echo "</tr>\n"; } } echo "</table>\n"; Questions Table: question_id q_text 1 Do you Like Red Color? 02A Do you Like Yellow Color? 02B Do you Like Blue Color? 3 Do you Like Green Color? 4 What color you like among them? 5 Do you Like Purple Color? 6 Do you Like Gold Color? 7 Do you Like Rose Gold Color? 8 Do you Like Black Color? 9 Do you Like Orange Color? The question 4, might be multiple answer. Feedback Table: question_id Expr2 Expr3 1 EMP1001 Yes 02A EMP1001 No 4 EMP1001 Red 4 EMP1001 Yellow 4 EMP1001 Blue 5 EMP1001 No 6 EMP1001 No 3 EMP1001 Yes 02B EMP1001 Yes 7 EMP1001 Yes 8 EMP1001 Yes 9 EMP1001 Yes 1 EMP1002 Yes 02A EMP1002 No 4 EMP1002 Red 5 EMP1002 No 6 EMP1002 Yes 3 EMP1002 Yes 02B EMP1002 Yes 7 EMP1002 No 8 EMP1002 9 EMP1002 Yes Result: Employee ID Do you Like Red Color? Do you Like Yellow Color? Do you Like Blue Color? Do you Like Green Color? What color you like among them? Do you Like Purple Color? Do you Like Gold Color? Do you Like Rose Gold Color? Do you Like Black Color? Do you Like Orange Color? EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 EMP1001 EMP1002 Expected Result: Employee ID Do you Like Red Color? Do you Like Yellow Color? Do you Like Blue Color? Do you Like Green Color? What color you like among them? Do you Like Purple Color? Do you Like Gold Color? Do you Like Rose Gold Color? Do you Like Black Color? Do you Like Orange Color? EMP1001 Yes No Yes Yes Red No No Yes Yes Yes EMP1001 Yes No Yes Yes Yellow No No Yes Yes Yes EMP1001 Yes No Yes Yes Blue No No Yes Yes Yes EMP1002 Yes No Yes Yes Red No Yes No Yes The question id no.4 will allow multiple choice to select, hence there will be multiple feedback for that particular question. foreach.txt
  10. Hi - can anyone help? I'm new to PHP land, and failing at this particular part. I have an image slider - where each image is contained in a div (e.g it is not a slider using ul and il...) It is will be used in a template for many pages, which will each have a varying number of images. There for I need to create a loop that say 'when there is no img url found, return to img 1' I'm stump. Currently this is beyond me ..... Or do I need to start from scratch? (ARGH!) Here is my function function getImage($num) { global $more; $more = 1; $link = get_permalink(); $content = get_the_content(); $count = substr_count($content, '<img'); $start = 0; for($i=1;$i<=$count;$i++) { $imgBeg = strpos($content, '<img', $start); $post = substr($content, $imgBeg); $imgEnd = strpos($post, '>'); $postOutput = substr($post, 0, $imgEnd+1); $postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);; $image[$i] = $postOutput; $start=$imgBeg+$imgEnd+1; } if(stristr($image[$num],'<img')) { echo '<a href="'.$link.'">'.$image[$num]."</a>"; } $more = 0; } and here's how I use it in the html: <div class="project-slider-mask w-slider-mask"> <div class="w-slide"> <?php getImage('1'); ?> </div> <div class="w-slide"> <?php getImage('2'); ?> </div> <div class="w-slide"> <?php getImage('3'); ?> </div> <div class="w-slide"> <?php getImage('4'); ?> </div> etc etc etc Help much much appreciated....been failing at this for so long!
  11. <?php function factorial($number) { if ($number < 2) { return 1; } else { return ($number * factorial($number-1)); } } function poisson($occurrence,$chance) { $e = exp(1); $a = pow($e, (-1 * $chance)); $b = pow($chance,$occurrence); $c = factorial($occurrence); return $a * $b / $c; } $x = 2.5; $y = 1.5; $calAll = array(); for($z = 0 ; $z <= 9 ; $z++) { array_push($calAll, (poisson($z,$x) * poisson(0,$y))*100, (poisson($z,$x) * poisson(1,$y))*100, (poisson($z,$x) * poisson(2,$y))*100 ); } $value = max($calAll); $key = array_search($value, $calAll); print_r($calAll) . "\n"; echo "max =",$value , " key =",$key . "\n";; ?> it is possible to find $z and the number 0,1 or 2 from the max of the returned array ? I used excel to perform this action and i found that for max=8.5854557290941 the $z is 2 and number 1 how to achieve this in php ?
  12. Here's a line. I want to add 100 more of same lines and increment the page numbers as shown below. I know I can just manually add 100 lines but Is there a way to do this with PHP that would make it easy? Or is this more of a javascript thing? // original $page1 = '<a href="?type='. $type_id .'&name='. $get_type_3_name_slug .'&page=1">1</a>'; // new $page1 = '<a href="?type='. $type_id .'&name='. $get_type_3_name_slug .'&page=1">1</a>'; $page2 = '<a href="?type='. $type_id .'&name='. $get_type_3_name_slug .'&page=2">2</a>'; $page3 = '<a href="?type='. $type_id .'&name='. $get_type_3_name_slug .'&page=3">3</a>'; $page4 = '<a href="?type='. $type_id .'&name='. $get_type_3_name_slug .'&page=4">4</a>'; $page5 = '<a href="?type='. $type_id .'&name='. $get_type_3_name_slug .'&page=5">5</a>'; ...etc
  13. Is it possible to append to cdatasection within xml file using a loop without creating a new cdata section with each loop thru. The code starts out by creating the basics for xml then enters into a loop to go thru each element of an array, appending the cdata. $xml=new DOMDocument('1.0', 'UTF-8'); $xml->preserveWhiteSpace = false; $xml->formatOutput = true; $components = $xml->createElement("components"); $name=$xml->createAttribute("name"); $name->value = "customEPGGrid"; $extends=$xml->createAttribute("extends"); $extends->value = "EPGGrid"; $components->appendChild($name); $components->appendChild($extends); $script = $xml->createElement("script"); $type=$xml->createAttribute("type"); $type->value = "text/brightscript"; foreach ($items as $item){ //ENTER INTO LOOP $cdata=$xml->createCDATASection(<<<EOT function init() m.content = createObject("RoSGNode","ContentNode") m.top.setFocus(true) dateNow = CreateObject("roDateTime") dateNow = dateNow.asSeconds() - 2000 addChannel({$item['name']}) addItem({$item['name']}, dateNow) m.top.content = m.content m.top.translation = [50, 300] m.top.numRows = 5 m.top.duration = 10800 m.top.nowNextMode = false m.top.infoGridGap = 0 m.top.channelInfoColumnLabel = "HELLO" end function sub addChannel(channelText as string) m.channel = m.content.createChild("ContentNode") m.channel.TITLE = channelText m.channel.HDSMALLICONURL = "http://css.boshanka.co.uk/wp-content/uploads/2015/04/icon-logo-design-small.png" end sub sub addItem(progText as string, timeStart) For i=0 To 5 Step 1 program = m.channel.createChild("ContentNode") program.TITLE = progText + str(i) program.PLAYSTART = timeStart + (i * 2000) program.PLAYDURATION = "2000" End For end sub EOT ); } $script->appendChild($cdata); $script->appendChild($type); $components->appendChild($script); $xml->appendChild($components); $xml->save($filename2); When executed like this, I get a new createCDATASection with each pass thru the loop. Not really wanting this, but one createCDATASection with different value or $item['name'].
  14. Hi, guys i'm trying to fetch all results from DB through a foreach loop. But it is not working as intended, as it brings only the first record and not the others. here is my code:- $sql1="select * from group_posts"; $stmt_t=$conn->prepare($sql1); $stmt_t->execute(); $data_fetch=$stmt_t->fetchAll(); foreach ($data_fetch as $row_d) { $postid=$row_d['gp_id']; $post_auth=$row_d['author_gp']; $post_type=$row_d['type']; $post_title= html_entity_decode($row_d['title']); $post_data= html_entity_decode($row_d['data']); $data1= array($post_data); // $data1= taggingsys($data0); $post_date=$row_d['pdate']; $post_avatar=$row_d['avatar']; $post_uid=$row_d['user_id']; if ($post_avatar != ""){ $g_pic='user/'.$post_uid.'/'.$post_avatar; } else { $g_pic='img/avatardefault.png'; } $user_image="<img src='{$g_pic}' alt='{$post_auth}' title='{$post_auth}' width='30' height='30'>"; $vote_up_count=$project->voteGroupCheck($postid, $_SESSION['id']); }
  15. Hello. Just a quick question about using a loop to create a string from post variables that will then be used in a query. I have several post variables submitted in a form, some of which contain a value of T. Others are not selected. In the database there are several columns which may contain values of T or may not. I would like to construct a query that searches for specific columns containing T and ignoring the rest. I'm using WHERE "T" IN(colnames). I need to get the column names into a comma separated string. Here's what I'm using: $postVal = array("1", "2", "3", "4", "5"); foreach ($postVal as $key=>$val){ $newVar = “col”.$val; if ($$newVar == "T") { *create/add to comma-separated string } else { *ignore } } I hope that seems clear enough. I'm just not sure if I'm on the right track or not. What do you think? Thank you, in advance!
  16. Hi, I am having a small issue with a front end html form, which through a series of looped input fields will update multiple WordPress posts at once, on submisson. The issue i'm having currently, is on submission it's only updating 1 post. I have found a solution to my problem, here: http://wordpress.stackexchange.com/questions/206372/how-to-handle-dynamic-form-data-with-repeating-fields But as i am still a bit of a novice, I have tried to apply the max_id solution to my code below, so far i've not got it to work. Using the solution on the above link, I don't suppose someone could show/tell me, what the code should be in it's entirety?? Including the foreach section, thanks! foreach( $testArray as $value ) { $post_information = array( 'post_title' => $value, 'post_status' => 'publish', // Choose: publish, preview, future, draft, etc. 'post_type' => 'predictions' //'post',page' or use a custom post type if you want to ); //update post wp_update_post($post_information);
  17. I have the following in a form that edits values already put into a dbase. $alev = array(1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => 'AP'); $dblev = explode(',',$row['hw_lev']); foreach ($alev as $key => $lev){ if(in_array($lev,$dblev)){ echo "<input type='checkbox' name='ud_lev[]' value='$lev' checked> $lev"; } else { echo "<input type='checkbox' name='ud_lev[]' value='$lev'> $lev"; } When I attempt to edit the dbase values, the following occurs: When I select the "A" checkbox, it is input into the database and reflects in the results. When I attempt to edit this, the "A" box is checked and all is well. When I select anything else AND "A" ("1", "A"), it is input into the database and reflects in the results. When I attempt to edit this, the "1" box is checked but the "A" box is NOT checked. This is what I need. I feel like the problem is with the array? But it could be the loop.. Probably something totally staring me in the face. You know how it goes. I was wondering if you see a problem in the array or in the loop. Any thoughts would be appreciated!
  18. Here's what I'm trying to do. I retrieve results using php foreach loop. Within that loop results, I want to show a div(.show-details) on mouse over only. How do I do that? This is my code so far. <style> .show-details { display: none; } </style> $get_records = $db->prepare("SELECT * FROM records WHERE record_id = :record_id"); $get_records->bindParam(':record_id', $record_id); $get_records->execute(); $result_records = $get_records->fetchAll(PDO::FETCH_ASSOC); if(count($result_records) > 0){ foreach($result_records as $row) { $get_record_title = $row['record_title']; $get_record_details = $row['record_details']; $get_record_price = $row['record_price']; ?> <div class="product"> <div class="product-title"> <?php echo $get_record_title; ?> </div> <div class="product-price"> <?php echo $get_record_price; ?> </div> </div> <div class="show-details"> <?php echo $get_record_details; ?> </div> <?php } } else { echo 'no results.'; } <script> $(document).ready(function() { $(".product").mouseover(function(){ $(".show-details").css("display", "block"); }); }); </script>
  19. Hi all, I am trying to calculate the straight line distance between two points by using their co-ordinates on each row from a mysql db that satisfies the query. It works fine, except the last for loop below calculates $lat[$x+1],$long[$x+1] to have blank fields as they no longer exist in the database therefore i have invalid distances calculated. My goal of this script is to find all the routes a particular day a flight attendant is working, by searching my db, rosters, then gathering the departure and arrival airport from this table. With these airports, I then extract their co-ordinates from the table, airports, and use the function below to calculate the distance. Hope it makes sense what I am trying to do below!! <?php function distance($lat1, $lon1, $lat2, $lon2, $unit) { $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $miles = $dist * 60 * 1.1515; $unit = strtoupper($unit); if ($unit == "K") { return ($miles * 1.609344); } else if ($unit == "N") { return ($miles * 0.8684); } else { return $miles; } } $today = '2016-01-04'; $sql = "SELECT * FROM rosters WHERE Code = 'TESTUSER' AND SectorDate = '$today' ORDER BY BeginTime ASC"; $result = mysqli_query($cxn,$sql) or die ("Cant get rosters distance."); $dep = array(); $arr = array(); $lat = array(); $long = array(); while($row=mysqli_fetch_array($result)) { $dep[] = $row['Dep']; $arr[] = $row['Arr']; } echo 'Number of flights: '.count($dep).'<br />'; foreach($dep as $key => $value) { $sql = "SELECT * FROM airports WHERE IATA = '$value'"; $result = mysqli_query($cxn,$sql) or die ("Cant get airport coordinates."); while($row=mysqli_fetch_array($result)) { $lat[] = $row['Latitude']; $long[] = $row['Longitude']; } } $max = count($dep); for ($x = 0; $x <= $max; $x++) { echo $dep[$x].' - '.$arr[$x].'<br />'; echo floor(distance($lat[$x],$long[$x],$lat[$x+1],$long[$x+1], "N")) . "nm<br />"; } ?>
  20. Say I have this loop. foreach($record as $row) { <div class="hello">Hello World!</div> } I want to loop through and add a letter alongside the "Hello World!" above. To do that, I found this code. $azRange = range('A', 'Z'); foreach ($azRange as $letter) { print("$letter\n"); } How can I combine the two loops so that I get a result like this? A Hello World! B Hello World! C Hello World! D Hello World! E Hello World! F Hello World!
  21. This is my database structure: http://www.awesomescreenshot.com/image/733881/57d01b042ca99b9a36dde90dd6640cdc I would like to loop through all the child elements (those who's parent_id is set to the data_id within the same table). Therefore those with "parent_id" as "0" are parents, and those with parent_id with a number in it is a child. I would like help creating a function that will generate tables, with the table itself as the parent, and all the rows within it would be children of that parent. There is only one layer of depth in this project (one parent and one child layer always. ). Can anyone help, or would want a more detailed description? Thank you, and looking forward to a reply.
  22. Hello - I hope I explain this clearly... I have some php code that presently displays 4 boxes in a row with images. When you click on a box/image, you go to a web post. The code goes to the bottom, sets the link, then loops back for the next image and repeats the process. What I'm trying to do is break this code apart so that that I can make each image go to a different link - basically set it up as html - image with link to a page. ( 4 of these) However, I don't want to break the code or the page that it displays ( our home page ) Here's the code snippet: <div id="new-classes" class="carousel slide"> <!-- Wrapper for slides ufff--> <div class="carousel-inner"> <?php $pieces=array_chunk($gallery,4); $j=0; foreach ($pieces as $slice) { echo '<div class="item '; if($j==0){echo 'active';} echo '">'; foreach ($slice as $i => $conte) { ?> <div class="col-sm-6 col-md-3" > <div class="new-class" > <img src="<?php echo $slice[$i]['image']; ?>" alt="//" /> <div class="class-title" > <div class="occult" > TEST this is where the specialities boxes link is <a <?php echo colors('a');?> href="<?php echo $slice[$i]['link']; ?>" class="link" ></a> I duplicated the above line and put in a specific link but it makes all the images go to the same page <a <?php echo colors('a');?> href="https://www.absolutept.com/tendinopathy/" class="link" ></a> --> </div> <h3 <?php echo colors('h3');?>><?php echo $slice[$i]['title']; ?></h3> <p <?php echo colors('p');?> class="occult" ><?php echo wp_trim_words(insert_br($slice[$i]['desc']),10,'...'); ?></p> </div> </div> </div> <?php } //end slice echo '</div>'; $j++; } // end pieces ?> </div> our homepage is absolutept.com -- these images are the "specialties" section 3/4 of the way down In the theme( wordpress) - there's an option to enter specialties ( custom post type ) which we did but we don't want these links to go to those special posts, we want them to go to the pages that the user can find in the main menu I know this is breaking the set up of the theme but if it's doable, we'd like to try First - any idea if it's doable and if so, thoughts on how? =) Thanks in advance.
  23. Hi, I am trying to add values together in my while loop, so far I have: $q->query($DB, $SQL); while($avrating=$q->getrow()): $averageratings = $avrating['sum(rating)'] / $noofreviews; $overallaverage = round($averageratings, 2) + round($averageratings, 2); echo '<p>'.$avrating['rating_name'].': '.round($averageratings, 2).'</p>'; endwhile; echo 'x'.$overallaverage; $overallaverage += $overallaverage / 10; echo 'The Average: '.$overallaverage; from this, I get: x7.34The Average: 8.074 the total shold be: 42.34 then dived by 10 should be 4.23
  24. Hi, I have 2 tables of data REVIEWS and RATINGS I would like to show a list of my reviews and a list of rating for each of my reviews I have tried putting my second WHILE loop inside teh first one but that doesn't work, can anyone please help? here is my code: $SQL = "SELECT * FROM school_reviews WHERE active = 1 AND is_deleted = 0 AND school_id = '" . $school_id . "' ORDER BY review_date DESC"; $q->query($DB,$SQL); while($review = $q->getrow()): $reviewid = $review['review_id']; echo $reviewid; echo '<h3>'.$review['review'].'</h3>'; endwhile; echo '<ul>'; $SQL = "SELECT * FROM ratings WHERE review_id = '".$reviewid."'"; $q->query($DB,$SQL); while($rating = $q->getrow()): echo '<li>'.$rating['rating_name'].': '.$rating['rating'].'</li>'; endwhile; echo '</ul>'; here is an example of the review I get: ReviewID: 46 Review: testing the reviews ReviewID: 43 Review: Because I know John is sooo handsome and he works at Cactus ReviewID: 40 Review: iuhi Ratings: Course / Course content: 5 Teacher: 5 Social Programme: 5 School Facilities: 5 Atmosphere: 5 Location: 5 Accommodation: 4 Service from Cactus: 2 Value for money: 3 Overall Experience: 5
  25. Hello so I have a simple code here that will check if a random number already exists in the database and will generate a new one: $rand = mt_rand(100000, 999999); $sid = array( ":sponsorID" => $rand ); $accounts = $db->select("accounts", "sponsorID = :sponsorID", $sid) while(count($accounts) > 0) { $newNum = mt_rand(100000, 999999); } What I wanted to do is to echo out $newNum. When I echo it out I get undefined index of that variable. How can I solve this?
×
×
  • 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.