PHP - Go Back To Beginning Of Loop?
$i = 0; while($i < 10) { if ($i == 7) { //Do Function } else { $i++ Go back to beginning of loop } //More if statements here. } Similar TutorialsHello, New to PHP and trying to loop through rows to and get the name of the "property" in this case. I have tried foreach and while and neither seem to want to return all rows by calling the function. Does it have something to do with echo'ing the table structure or can I not return an array out of a function like this? I commented out the while loop as that wasn't working and put in a foreach loop though that didn't return all the data either. Any help is greatly appreciated Code: [Select] <?php function getProperties(){ $sql = "SELECT propertyName FROM properties;"; $result = mysql_query($sql); //$count = mysql_num_rows($result); $property = mysql_fetch_array($result); foreach($property as $propertyName){ echo "<td width=\"157\" height=\"24\" valign=\"middle\"><div align=\"left\"><input type=\"checkbox\" name=\"$propertyName\" \"id=\"$propertyName\" />$propertyName</div></td>"; } /* for($i=0;$i>=$count;$i++){ while($property = mysql_fetch_array($result)){ $propertyName = $property['propertyName']; echo "<td width=\"157\" height=\"24\" valign=\"middle\"><div align=\"left\"><input type=\"checkbox\" name=\"$propertyName\" \"id=\"$propertyName\" />$propertyName</div></td>"; } } */ } ?> Please, take a look to the following code.After clicking Next it goes to overview.php.Why when I click back on my browser to return to this page again, it is not returning back? When I click back I receive "Confirm Form Resubmission" message. After refreshing page it loads page. I guess problem is in "session_start();" part. Something to do with cookies. Please, help me it is very urgent for me. <?php session_start(); echo "<html> <head> <title>Hello World</title> <meta http-equiv='Content-Type' content='text/html; charset=Windows-1252'/> </head>"; require_once ('functions.inc'); if(!isset($_POST['userid'])) { echo "<script type='text/javascript'>"; echo "window.location = 'index.php'"; echo "</script>"; exit; }else{ session_register("userid", "userpassword"); $username = auth_user($_POST['userid'], $_POST['userpassword']); if(!$username) { $PHP_SELF = $_SERVER['PHP_SELF']; session_unregister("userid"); session_unregister("userpassword"); echo "Authentication failed " . "Please, write correct username or password. " . "try again "; echo "<A HREF=\"index.php\">Login</A><BR>"; exit; } } function auth_user($userid, $userpassword){ global $default_dbname, $user_tablename; $user_tablename = 'user'; $link_id = db_connect($default_dbname); mysql_select_db("d12826", $link_id); $query = "SELECT username FROM $user_tablename WHERE username = '$userid' AND password = '$userpassword'"; $result = mysql_query($query) or die(mysql_error()); if(!mysql_num_rows($result)){ return 0; }else{ $query_data = mysql_fetch_row($result); return $query_data[0]; } } echo "hello"; echo "<form method='POST' name='myform' action='overview.php'>"; echo "<input type='submit' value='Next'>"; echo "</form>"; ?> I'm reading through this book which is actually not bad but, on page 286 there's a shopping_cart.php code (which I downloaded from the web site). The code that seems relevant to me is this: <?php $totalPrice = 0; foreach ( $_SESSION["cart"] as $product) { $totalPrice += $product->getPrice(); //<<<LINE 94 ?> The error I get is Fatal error: Call to a member function getPrice() on a non-object in C:\usr\web\shopping_cart.php on line 94 Should $product be a cast to the Product object? class Product { private $productId; private $productName; private $price; public function __construct( $productId, $productName, $price ) { $this->productId = $productId; $this->productName = $productName; $this->price = $price; } public function getPrice() { return $this->price; } //etc. } The below code returns a radio list after an input box in a profile edit section. All I want to do is add a space at the beginning of the radio list so to separate the input box and the radio list. Where the magic happens here is on this line: return $selhtml . ' ' . getFieldIcons( $_CB_framework->getUi(), $required, null, $fieldHandler->getFieldDescription( $field, $user, $output, $reason ), $fieldHandler->getFieldTitle( $field, $user, $output, $reason ) ); I've tried several variations of trying to use &nspb; both in the return string directly as well as creating a var for it. I've tried various ways of wrapping it in a div to simply add a margin, I've tried kicking my dog, I've tried banging my head against the wall, nothing seems to work. I either get a t var error, an unexpected something or other like . or & error depending on what I'm doing, or it tries to divide by zero using /'s. Here's a larger view of the code: function onFieldIcons( &$fieldHandler, &$field, &$user, $output, $reason, $tag, $type, $value, $additional, $allValues, $displayFieldIcons, $required ) { global $_CB_framework, $ueConfig, $_CB_fieldIconDisplayed; if ( is_object( $field->params ) ) { $privacyLevel = $field->params->get( 'plug_cbprivacy_level' ); } else { $privacyLevel = 0; } if ( $displayFieldIcons && ( $reason != 'search' ) ) { if ( ( $privacyLevel == 1 ) && ( $field->profile != 0 ) ) { $privacy =& moscomprofilerPrivacy::getInstance( $user, 'field', $field->fieldid ); $selected = ( $privacy ? $privacy->rule : '' ); $selectorName = $field->name . '___cbprivacy'; $connTypes = array(); if ( $this->params->get( 'conns_by_type', 0 ) ) { if ( $ueConfig['connection_categories'] ) { $connTypes = explode( "\n", $ueConfig['connection_categories'] ); foreach ( array_keys( $connTypes ) as $k) { $connTypes[$k] = trim( $connTypes[$k] ); } } if ( $selected == 2 ) { $type = $privacy->getParam( 'conn_cat' ); if ( $type ) { $selected = $selected . '|*|' . $type; } } } $options = array(); $options[] = moscomprofilerHTML::makeOption( '', '' . CBTxt::T(' ') ); if ( ( $ueConfig['allow_profileviewbyGID'] == -2 ) && $this->params->get( 'prop_registered', 1 ) ) { $options[] = moscomprofilerHTML::makeOption( '1', '' . CBTxt::T(' ' ) ); } if ( $ueConfig['allowConnections'] ) { $prop_connections = $this->params->get( 'prop_connections', 1 ); if ( $prop_connections ) { $options[] = moscomprofilerHTML::makeOption( '2', '' . CBTxt::T( ' ' ) ); } if ( count( $connTypes ) > 1 ) { foreach ($connTypes as $type ) { $options[] = moscomprofilerHTML::makeOption( '2|*|' . htmlspecialchars( $type ), ( $prop_connections ? ' ⌊ ' : '' ) . '' . sprintf( CBTxt::T( 'Only for %s' ), $type ) ); } } if ( $this->params->get( 'prop_fofs', 1 ) ) { $options[] = moscomprofilerHTML::makeOption( '3', '' . CBTxt::T( 'Also for friends of friends' ) ); } } if ( $this->params->get( 'prop_invisible', 1 ) ) { $options[] = moscomprofilerHTML::makeOption( '99', '' . CBTxt::T( ' ' ) ); } $selHtml = moscomprofilerHTML::radioList( $options, $selectorName, '', 'value', 'text', $selected, 2, false ); if ( isset( $_CB_fieldIconDisplayed[$field->fieldid] ) ) { return $selHtml; } else { $_CB_fieldIconDisplayed[$field->fieldid] = true; return $selHtml . ' ' . getFieldIcons( $_CB_framework->getUi(), $required, null, $fieldHandler->getFieldDescription( $field, $user, $output, $reason ), $fieldHandler->getFieldTitle( $field, $user, $output, $reason ) ); } } else { if ( isset( $_CB_fieldIconDisplayed[$field->fieldid] ) ) { return null; } else { $_CB_fieldIconDisplayed[$field->fieldid] = true; return getFieldIcons( $_CB_framework->getUi(), $required, $field->profile, $fieldHandler->getFieldDescription( $field, $user, $output, $reason ), $fieldHandler->getFieldTitle( $field, $user, $output, $reason ) ); } } } else { return null; } } The basic layout here is this: |inputbox||radio list| But I want: |inputbox| |radio list| Here is my current code to display files from the end to beginning : Code: [Select] <?php function func() { $date = date("Y-m-d"); $picarray = array(); $userarray = array(); $handle = opendir ('pqimages/'.$date.'/'); while (false !==($file = readdir($handle))) { if($file != "." && $file != "..") { $picarray[] = "http://blah.com/pqimages/".$date."/".$file.""; $userarray[]= "pqimages/".$date."/".$file.""; } } sort($picarray); sort($userarray); closedir($handle); $json_array = json_encode($picarray); echo $json_array; } func(); ?> How could I change this from end to beginning for ($picarray)? Cheers, George My first post.
I am trying to import images related to a particular listing ID. Currently, I have to enter the number of available photos into a db table, and run the following loop;
<section id="photos">
<?php
$b = $row['PIX'];
for ( $a = 01; $a <= $b; $a++ ) { echo "<a href=\"../imgs/{ $row[ 'ID' ] }-" . { $a } . ".jpg\" ><img src=\"../imgs/{ $row[ 'ID' ] }-" . { $a } . "_tn.jpg\" /></a> " ; } ?> </section> I would like to find a way to import all the images that begin with the $row[ 'ID' ], but without me having to enter/store { $b } (the number of images recorded in the db). How can I accomplish this? _ Hi, I have two variables: $latest_note and $notes. Whenever I update $latest_note, I also want this (and today's date) to be added to $notes, such that $notes becomes a sort of archive of all of the latest notes, listed by date. I tried creating a third variable called $full_notes and saying $full_notes = $latest_note.$notes; ... then when I run my mysql update, I set notes='$full_notes' but it's not working properly. Is there a way to simply add one variable to the beginning of another in the db directly, concatenating the two? Thanks! Hello, I have this XML file I am parsing and I have hit a small formatting issue that I can't seem to get around.
Here is what the the output of the RSS looks like.
<description><![CDATA[<div style='text-align:left;'>Exit ramp closed. <br/><b>Current Status:</b> Open<br/><b>Affected Lanes:</b> Exit Ramp<br/><b>Dates:</b> Wednesday, May 28 - Thursday, May 29<br/><b>Days Closed:</b> <font color='#808080'>S</font><font color='#808080'>M</font><font color='#808080'>T</font><font color='#FF0000'><b>W</b></font><font color='#FF0000'><b>T</b></font><font color='#808080'>F</font><font color='#808080'>S</font> 20:00 PM - 6:00 AM</div>]]></description>Notice at the first is "Exit ramp closed." There is nothing before it but, for some weird reason when I parse it. It is on a new line like so, notice it should be up there with "Incident" but, it is dropped down below it. Incident: Exit ramp closed. Current Status: Open Affected Lanes: Exit Ramp Dates: Wednesday, May 28 - Thursday, May 29 Days Closed: SMTWTFS 20:00 PM - 6:00 AMThis is how it is formated in the td cell. <td style='{$td2Style}'><strong>Incident:</strong> {$incident_data_desc}</td>\n";So as you can see above, there is nothing before it that would cause it to break to a new line both in the table or in the RSS. So how can I remove that first return only is that is on the same line with it and not below it. I have tried this and a couple of other things like trim with no luck. $description = $item->description; $incident_data_desc = str_replace("\r", '', $description );Note, I only need that first one removed, the others are fine. I can do it but it will remove all the breaks and I only want to remove that first one that is causing the line to be on a new line. Any suggestions? -Thanks I keep getting errors that are associated with one-off and one-time occurrences. I want to tell the script to just restart itself from the beginning if it encounters any type of error, whether it by a fatal error, or any other kind. is there a way to do this? Hi, I've always used PHP code in my websites in a procedural manner as I come from a html/css background. Now that I want to do projects with more complexity I'm thinking I need to approach development in a more Object Oriented fashion. My question is more a theoretical one. I'm creating a User class and I'm not sure on what is the best practise for putting my functions etc. and where to call them. My project will have 2 different users (Admin & End User) so is it correct to say that the User class should encapsulate all the functions of both of these users ? By that I mean create/delete/modify user, login & change password/forgotten password functionality rather than having a seperate Login class Should I only call the database functions within these methods of the user class as opposed to calling them on the php page where the form data is posted ? For example, if a user logins in and when the form data is posted I currently open a connection, validate data, run the query. In an OO approach would I have just one User class method thats relevant to a particular page functionality ? Say, in pseudo code, for handling a login request loginRequest.php Code: [Select] include User class try { create new user User(); User::login(); } catch Exception() and should my User class look something like this class.User.php Code: [Select] include DBase class class User { var name, var email, var password, function validateInput (email, password) { if (!valid input) throw Exception else return true } function login (email, password){ try { database connection validateInput(); sql to see if user exists and login } catch Exception } } Apologies for this being a bit long winded! thanks tmfl This is my code: $episodes = mysql_query("SELECT * FROM episode_links WHERE episode_id = '".$episode_id."' AND moderated='1' ORDER BY host ASC"); while ($episode = mysql_fetch_assoc($episodes)) { // code here } and in my host table, I have values like this: Fileserve.com MegaUpload.com Rapidshare.com Torrent And I would like a way to sort this so that only the Fileserve links appear on the top ( the first few results), then all the others. can anyone help me? Hello guys, im using this code atm and it's working, but the new rows created are put in the end of the table. I want them to stack up from the beginning pushing older rows down. What should i do to make that work? <?php $con = mysql_connect("localhost","*****","*******"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ananaz_se", $con); $sql="INSERT INTO stuff (adult, namn, url) VALUES ('$_POST[adult]','$_POST[namn]','$_POST[url]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 row added"; mysql_close($con) ?> I have a regex that validates a string.
I want to ensure there is no space in the string.
Thus far I have used the negative look ahead regex construct as shown below to match strings without spaces.
(?!.*(\s))While this prevents space in between a word, all strings with space characters at the end or beginning are getting validated. I do not want that at all. This is the full regex script below: $string = "#JebiamgoOeing0"; if (preg_match('/^.*(?=.{8,})(?!.*([A-Za-z0-9])\1{1})(?=.*[a-z])(?=.*[A-Z])(?!.*(\s))(?=.*[\d])(?=.*[\W]).*$/', $string)) { "do something"; } else { "do something else"; }I need help in resolving this. Thank you. Edited by terungwa, 25 October 2014 - 12:50 PM. I've inherited a website (www.bonniebakerlaw.com) and have found that the previous web developer had left the contact form in quite a shambles. As you can see it attempts to use a Captcha to validate users, but does not in fact work! I can leave the entire form blank (including the captcha) and still get to the "Thank You" page indicating the form was correctly submitted (This does not, in fact, actually generate an email correctly)! So before I delve into "Head First PHP & MySQL" to debug and correct the error, I was wondering if some kind person(s) would be good enough to point me to the relevant sections / documentation highlighting the fundamentals of building this type of form correctly coupled with the use of a Captcha as noted. Some code has been REDACTED to protect the innocent. I won't post the HTML of the form as it's available from the web site and is a fairly simple HTML construct. Form Code: Code: [Select] <?php require_once('recaptchalib.php'); // Get a key from https://www.google.com/recaptcha/admin/create $publickey = "REDACTED PUBLIC KEY"; $privatekey = "REDACTED PRIVATE KEY"; # the response from reCAPTCHA $resp = null; # the error code from reCAPTCHA, if any $error = null; # was there a reCAPTCHA response? if ($_POST["recaptcha_response_field"]) { $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if ($resp->is_valid) { echo "You got it!"; } else { # set the error code so that we can display it $error = $resp->error; } } echo recaptcha_get_html($publickey, $error); ?> "Thank You" page Code: Code: [Select] <?php $visitor = $_REQUEST['visitor'] ; $visitormail = $_REQUEST['visitormail'] ; $State = $_REQUEST['State:'] ; $Address = $_REQUEST['StreetAddress'] ; $City = $_REQUEST['City:'] ; $Zip = $_REQUEST['Zip:'] ; $Phone = $_REQUEST['Phone:'] ; $Fax = $_REQUEST['Fax:'] ; $Emailed = $_REQUEST['Emailed'] ; $Phoned = $_REQUEST['Phoned'] ; $Faxed = $_REQUEST['Faxed'] ; $Postaled = $_REQUEST['Postaled'] ; $Description = $_REQUEST['IssueDescription'] ; if ($Emailed == "y") { $req1 = " Email \n" ; } if ($Phoned == "y") { $req2 = " Phone \n"; } if ($Faxed == "y") { $req3 = " Fax \n"; } if ($Postaled == "y") { $req4 = " Postal Mail \n"; } $req = $req1 . $req2 . $req3 . $req4 ; $message = "name: $visitor email: $visitormail Address: $Address City: $City State: $State Zip: $Zip Phone: $Phone Fax: $Fax Requested contact by: $req Description: $Description " ; mail("redacted@somedomain.com", "redacted@somedomain.com: contact page", "$message", "From: $visitormail" ) ; ?> 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? hi... i have a table ... i add and remove data in the table...when i add new record , information add to center of the table ! whats problem? i want add data in first of table. please guide me.thanks
Hello, i have two fields. a beginning year and an ending year. How can i make new fields out of the years in between the beginning and ending years. i hope that makes sense. 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 |