PHP - How To Loop Through A Query
Hi
Could do with some help. I have 20 clients (client-1, client-2, client-3) and so on. Each client makes several calls per day. How can I get a row count from two columns (Date, clid) and echo the count for each client? Similar TutorialsThis topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=306079.0 So I output the Threads for my forum onto the main screen like so <div class ='grid-container'> <?php //Get the Threads and output them onto the screen in a grid container $query = mysqli_query($conn, "SELECT * FROM Threads order by id desc") or die (mysqli_error($conn)); $GetPostsQuery = mysqli_query($conn, "SELECT Count(*) FROM Posts") or die (mysqli_error($conn)); while ($row = mysqli_fetch_array($query)) { $imageURL = 'upload/Thumbnails/'.rawurlencode($row["filename"]); $PostBody = nl2br($row['ThreadBody']); echo " <div class ='grid-item'> <div class='ThreadComment'> Comments: <br> </div> <div class='ThreadNumber'> Post {$row['id']}<br> </div> <h2><a href='viewthread.php?id={$row['id']}'> {$row['Title']} </a></h2> <div class ='img-block'> <img src={$row['$imageURL']}$imageURL alt='' /> </div> <p>$PostBody </p> </div> \n"; } ?> However I don't keep the count of comments against the threads on my Threads table. I've attached a "describe" of both my comments (named Posts) and my Threads table (name Threads) I want to output the count of the comments against each Post in the above While loop To obtain the amount of comments against a thread I can get this from SQL by doing select count(IdOfThread) from Posts where id='169' ; But how would I access a query in SQL for the Posts table whilst it's already querying the Threads table? How would I implement this into the above while loop? Many thanks (and my db design maybe incorrect I'm very new )
Basically, this part of the code is checking the "scanned" table in my mysql database to get the last scanned date for the item at hand. It then takes that date and selects all the vendor items in the odbc table "ARVEND" that are greater than the last purchase date. || This is where I am running into a problem. When it loops through each vendor item it selects from the "associated" mysql table to see if the vendor item has been scanned. If it does not find anything I am trying to get the $checkpurdate variable to add 1 to itself. | In the second script you will see the elseif($checkpurdate>0) .... Here I am saying if there are any vendor items that have not been scanned, highlight the row in yellow. But, this part of my code $checkpurdate = $checkpurdate + 1; does not seem to be counting correctly. Sometimes it counts '4' for an item when there are only two vendor items available. All of this may sound confusing since you may not know what I am trying to do. But, the main problem I am having is the counting part is returning wrong numbers. $checkpurdate = $checkpurdate + 1; Code: [Select] /* $checkpurdate */ $query3 = "SELECT date FROM scanned WHERE `item` = '$ITEM' ORDER BY date DESC LIMIT 1"; $result3 = mysql_query($query3); $checklastdate = ""; while($row3 = mysql_fetch_array($result3, MYSQL_ASSOC)) {$checklastdate= $row3['date']; $checklastdate=date("m/d/y", strtotime($checklastdate)); } //checkpurdate loops $checkassoc="0"; $checkpurdate="0"; $sqlc="SELECT RECNO5 FROM ARVEND WHERE PURDATE1 > '$checklastdate' AND ITEM = '$ITEM'"; $rsc=odbc_exec($conn,$sqlc); if (!$rsc) {exit("Error in SQL");} while (odbc_fetch_row($rsc)) { $checkrecno5=odbc_result($rsc,"RECNO5"); $checkassosquery = "associated WHERE `VENDORID` = '$checkrecno5' AND ITEM = '$ITEM'"; $checkassoc = get_rows($checkassosquery); if($checkassoc>0) { // do nothing } else { $checkpurdate = $checkpurdate + 1; } } Code: [Select] elseif($checkpurdate>0) { echo"<TR class=\"NV\"> <TD>"; } I am in the process of making a stream page where users can enter a status, like and comment others statuses, like on facebook.
I have 4 tables, stream, users, likes and comments as shown below, with the rows I will be using:
stream stream_status What I am trying to do is query a database using a loop conditional and return the data but my code only repeats the first instance multiple times! My code is below, I have tried to use comments to explain what should be happeing! $rows = null; $q1 = "SELECT * FROM table"; $r1 = mysql_query($q1) or die(mysql_error()); $i = 1; while($i <= 5){ $start = (1000 * $i); $end = ($start + 1000); while($a1 = mysql_fetch_array($r1, MYSQL_ASSOC)){ /* query the database where 'start' is >= 1000 and where 'end' is <= 2000, this should loop so the next time is where 'start' >= 1000 * $i should be 1000 then 2000, 3000 etc... and where 'end' should be 2000, 3000, 4000 etc... */ if($a1['start'] >= $start && $a1['end'] <= $end){ $rows .= $a1['col1'].':'.$a1['col2']."\n"; } } echo nl2br(trim($rows.'<p>')); $i++; } /* The problem is that it always shows multiple instances of the first result only where start = 1000 and end = 2000 */ Any help would be much appreciated!! I've created a function getsub(). The idea is that this function contains a query that grabs records from the categories table, using the $row['cat_id'] that I pass to it from within an existing while ($row=mysql_fetch_assoc($res)) loop. Heres the function: function getsub($rowid,$catsort) { global $system, $LANGUAGES, $subres; $subquery = "SELECT * FROM webid_categories WHERE parent_id = " . $rowid . " " . $catsort; $subres = mysql_query($subquery); $system->check_mysql($subres, $subquery, __LINE__, __FILE__); return $subres; } And heres the code that calls this function and passes the $row['cat_id'] value to it: // prepare categories list for templates/template // Prepare categories sorting if ($system->SETTINGS['catsorting'] == 'alpha') { $catsorting = ' ORDER BY cat_name ASC'; } else { $catsorting = ' ORDER BY sub_counter DESC'; } $query = "SELECT cat_id FROM " . $DBPrefix . "categories WHERE parent_id = -1"; $res = mysql_query($query); $system->check_mysql($res, $query, __LINE__, __FILE__); $query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . mysql_result($res, 0) . " " . $catsorting . " LIMIT " . $system->SETTINGS['catstoshow']; $res = mysql_query($query); $system->check_mysql($res, $query, __LINE__, __FILE__); while ($row = mysql_fetch_assoc($res)) { $subcats = getsub($row['cat_id'],$catsorting); while($subrow = mysql_fetch_assoc($subcats){ $template->assign_block_vars('sublist', array( 'SID' => $subrow['cat_id'], 'SNAME' => $category_names[$getrow['cat_id']] )); } $template->assign_block_vars('cat_list', array( 'CATAUCNUM' => ($row['sub_counter'] != 0) ? '(' . $row['sub_counter'] . ')' : '', 'ID' => $row['cat_id'], 'IMAGE' => (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '', 'COLOUR' => (empty($row['cat_colour'])) ? '#FFFFFF' : $row['cat_colour'], 'NAME' => $category_names[$row['cat_id']] )); } then a .tpl file just references the {sublist.SID} and {sublist.SNAME} variables. BUT.... It ain't working. My page just goes blank. Any help would be massively appreciated. Have a web page that displays a number of update forms depending on the amout of records that get returned from a mysql query, if query returns 4 records then the page will display 4 identical forms, the trouble i'm having is getting the each of the 4 forms to display a different record as at the moment they all show just first record of query. I have played around with loops but not getting anywhere which may be due to my limited knowledge code for page is below Code: [Select] <?php $numberofrow =mysql_num_rows($Recordset1); for($counter = 1;$counter<=$numberofrow;$counter++){ ?> <label for="hometeam2"></label> <form id="form1" name="form1" method="POST" action="<?php echo $editFormAction; ?>"> <label for="hometeam"></label> <input name="fixid" type="text" id="fixid" value="<?php echo $row_Recordset1['FixtureID']; ?>" /> <input name="hometeam" type="text" id="hometeam2" value="<?php echo $row_Recordset1['hometeamname']; ?>" /> <label for="homescore"></label> <input name="homescore" type="text" id="homescore" value="<?php echo $row_Recordset1['homescore']; ?>" /> <label for="awayscore"></label> <label for="fixid"></label> <input name="awayscore" type="text" id="awayscore" value="<?php echo $row_Recordset1['awayscore']; ?>" /> <label for="awayteam"></label> <input name="awayteam" type="text" id="awayteam" value="<?php echo $row_Recordset1['awayteamname']; ?>" /> <input type="submit" name="update" id="update" value="Submit" /> <input type="hidden" name="MM_update" value="form1" /> mysql_query("update pupils set record='running' where pid !='$testing[0]' I'm a bit of a newb to PHP and MySQL. I seem to be having an issue with something. How do I loop through an array, querying each value in the array until the query meets a certain condition.. In this case it would be that the number of rows returned from the query is less than five. Here is what I have: $query1="SELECT UserID FROM Users where RefID='$userid'"; $result1=mysql_query($query1); while ($row = mysql_fetch_array($result1, MYSQL_NUM) && $sql2querynum < '5') { echo ($row[0]); echo " "; $sql2 = "SELECT * FROM Users WHERE RefID=$row[0]"; $sql2result = mysql_query($sql2); $sql2querynum = mysql_numrows($sql2result); } Problem is, for every value it echoes out, I get the following warning: mysql_numrows(): supplied argument is not a valid MySQL result resource Like I said, I'm a newbie to PHP to maybe I'm not even going about doing this the right way. Hoping someone can help to point me in the right direction. Hi, Here is an extract of my while loop while ($personquery = mysql_fetch_array($personfetch, MYSQL_ASSOC)) { echo "$personfetch[first_name]"; } This will list each person now I want to do an INSERT to the database on every single member that is being listed I can only get it to INSERT for the one. Thanks I am trying to create 3 columns of data from a query. I have used this code before for 2 columns but and now wanting to use for three columns.
There are 5 records from a join query. The first two columns display the results, 2 results in the left column and 3 results in the center column. The right column displayw empyt text used in displaying the results, there is no data to populate and it seems to mimic the the number from the center, 3.
Here is the URL to see the problem
http://specialslocat...ignID=1IBu3992p
Here is the Code for the query and the 3 column results.
<?php $UN_URL = $_GET['un']; $mS_MGMTcampaignID_URL = $_GET['mS_MGMTcampaignID']; ?> <table width="944" border="1" align="center" cellpadding="0" cellspacing="0"> <?php $result = mysql_query( "SELECT * FROM manager_Specials_company_mgmt MSCM LEFT JOIN b2c_coupons B2CC ON (MSCM.mS_MGMT_id = B2CC.m_primeID )WHERE mS_MGMTcampaignID = '$mS_MGMTcampaignID_URL' ORDER BY mS_MGMT_m_company ASC" ); $num_results = mysql_num_rows($result); $numb_tb_rows= ceil($num_results/3) ?> <? if ( $numb_tb_rows > 0 ) { ?> <tr > <td colspan="4" valign="top" class="body_text_10_Center"><strong><?=$mS_campaignName_mS?> is proud to sponsor <?=$num_results?> <? if ( $num_results == 1 ) { ?> company:</strong> <? } elseif ( $num_results > 1 ) { ?> companies:</strong> <? } ?> </td> </tr> <tr class="body_text_10_Center"> <!-- Column 1 --> <td width="320" class="body_text_10_Center" valign="top"> <? // column #1 if($num_results>=1) { for($i=0; $i<$numb_tb_rows; $i++) { $row= mysql_fetch_array($result); ?> <?php if(!empty ($row["m_logo"])) { ?> <div align="center"> <img src="http://marketingteammates.com/_ZABP_merchants/_zcnsLogos/gick.php/<?=stripslashes($row["m_logo"])?>?resize(220)" border="0"></a><br /> </div> <?php } else { } ?> <h6><?=stripslashes($row["mS_MGMT_m_company"])?></h6> <?=stripslashes($row["b2c_m_address1"])?> <?=stripslashes($row["b2c_m_address2"])?><br /> <?=stripslashes($row["b2c_m_city"])?> <?=stripslashes($row["b2c_m_state"])?>, <?=stripslashes($row["b2c_m_zip"])?><br /> Phone: <?=stripslashes($row["b2c_m_phone"])?><br /> Fax: <?=stripslashes($row["b2c_m_fax"])?><br /> <a href="mailto:<?=stripslashes($row["b2c_email"])?>"><?=stripslashes($row["b2c_email"])?></a><br /><br /> Hours of Operation: <?=stripslashes($row["m_coupon_title"])?><br /> <?=stripslashes($row["m_coupon_desc"])?><br /><br /> <div align="center"> <img src="../images/print_image.gif" width="29" height="31" /><br /><br /> <hr width="80%" size="1" /> </div><br /><br /> <? // END column #1 } } ?> </td> <!-- Column 2 --> <td width="320" class="body_text_10_Center" valign="top"> <? // column #2 if($num_results>=2) { for($i=($numb_tb_rows); $i<$num_results; $i++) { $row= mysql_fetch_array($result); ?> <?php if(!empty ($row["m_logo"])) { ?> <div align="center"> <img src="http://marketingteammates.com/_ZABP_merchants/_zcnsLogos/gick.php/<?=stripslashes($row["m_logo"])?>?resize(220)" border="0"></a><br /> </div> <?php } else { } ?> <h6><?=stripslashes($row["mS_MGMT_m_company"])?></h6> <?=stripslashes($row["b2c_m_address1"])?> <?=stripslashes($row["b2c_m_address2"])?><br /> <?=stripslashes($row["b2c_m_city"])?> <?=stripslashes($row["b2c_m_state"])?>, <?=stripslashes($row["b2c_m_zip"])?><br /> Phone: <?=stripslashes($row["b2c_m_phone"])?><br /> Fax: <?=stripslashes($row["b2c_m_fax"])?><br /> <a href="mailto:<?=stripslashes($row["b2c_email"])?>"><?=stripslashes($row["b2c_email"])?></a><br /><br /> Hours of Operation: <?=stripslashes($row["m_coupon_title"])?><br /> <?=stripslashes($row["m_coupon_desc"])?><br /><br /> <div align="center"> <img src="../images/print_image.gif" width="29" height="31" /><br /><br /> <hr width="80%" size="1" /> </div><br /><br /> <? // END column #2 } } ?> </td> <!-- Column 3 --> <td width="320" class="body_text_10_Center" valign="top"> <? // column #3 if($num_results>=3) { for($i=($numb_tb_rows); $i<$num_results; $i++) { $row= mysql_fetch_array($result); ?> <?php if(!empty ($row["m_logo"])) { ?> <div align="center"> <img src="http://marketingteammates.com/_ZABP_merchants/_zcnsLogos/gick.php/<?=stripslashes($row["m_logo"])?>?resize(220)" border="0"></a><br /> </div> <?php } else { } ?> <h6><?=stripslashes($row["mS_MGMT_m_company"])?></h6> <?=stripslashes($row["b2c_m_address1"])?> <?=stripslashes($row["b2c_m_address2"])?><br /> <?=stripslashes($row["b2c_m_city"])?> <?=stripslashes($row["b2c_m_state"])?>, <?=stripslashes($row["b2c_m_zip"])?><br /> Phone: <?=stripslashes($row["b2c_m_phone"])?><br /> Fax: <?=stripslashes($row["b2c_m_fax"])?><br /> <a href="mailto:<?=stripslashes($row["b2c_email"])?>"><?=stripslashes($row["b2c_email"])?></a><br /><br /> Hours of Operation: <?=stripslashes($row["m_coupon_title"])?><br /> <?=stripslashes($row["m_coupon_desc"])?><br /><br /> <div align="center"> <img src="../images/print_image.gif" width="29" height="31" /><br /><br /> <hr width="80%" size="1" /> </div><br /><br /> <? // END column #3 } } ?> </td> </tr> <? } else { echo ""; } ?> </table>Thanks for any help in advance. Mike I am really just a beginner in PHP but I've got a task to create a simple hotel booking system by using PHP and MySQL. It works in several steps, described in separate .php files. All of them seem to work fine, except the last one. In this last file I want to add all the data into a MySQL database table. I would like to do this by creating a record for each date, a guest is spending in a hotel (so that when booking, another loop checks whether the room is not occupied yet for that date). I decided to use a for-loop for that, but it doesn't seem to be working (the records just don't get inserted into the table). I checked all the variables by echo-ing them and they are all right. I also tried the query without the loop and it works as well. So I guess there is some other problem. This particular .php file looks as follow: <?php session_start(); include('db_config.php'); $name=($_POST['name']); $telephone=addslashes($_POST['telephone']); $email=addslashes($_POST['email']); $code=md5($email.time()); $checkout_date=$_SESSION['checkout']; $checkin_unix=$_SESSION['checkin_unix']; $checkout_unix=$_SESSION['checkout_unix']; $roomtype=$_SESSION['roomtype']; $checkin_date=$_SESSION['checkin']; for ($stay_date=$checkin_unix; ; $stay_date=$stay_date+24*60*60) { if ($stay_date=$checkout_unix){ break; } mysql_query("INSERT INTO reservations VALUES( '', '$roomtype', 'pending', 'date ('d/m/Y', $stay_date)', '$stay_date', '$checkout_date', '$name', '$telephone', '$email', '$code' )"); } ?> I would appreciate any kind of help, any idea. I have a table called "playlists", and a table called "musics". In the musics table, there is a column playlist_id which references the playlist that each music is contained.
I'm using api calls to display information on the site with JavaScript, so I need to return a JSON.
I need the json with the following structu
[
Playlists: [
{
Name: "etc",
musics: [
{
name: "teste.mp3" }, { name: "test2.mp3" } ] }, ... ] ] And this is my code: $query = $con->prepare("SELECT * FROM playlists WHERE user_id = :id");
$start = 0; I have a php script that I've been running that seems to have been working but now I'm wondering if some of my logic is potentially off. I select records from a db table within a date range which I put into an array called ```$validCount``` If that array is not empty, that means I have valid records to update with my values, and if it's empty I just insert. The trick with the insert is that if the ```STORES``` is less than the ```Quantity``` then it only inserts as many as the ```STORES``` otherwise it inserts as many as ```Quantity```. So if a record being inserted with had Stores: 14 Quantity:12
Then it would only insert 12 records but if it had It would only insert 1 record. In short, for each customer I should only ever have as many valid records (within a valid date range) as they have stores. If they have 20 stores, I can have 1 or 2 records but should never have 30. It seems like updating works fine but I'm not sure if it's updating the proper records, though it seems like in some instances it's just inserting too many and not accounting for past updated records. This is the logic I have been working with:
if(!empty($validCount)){ for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $out[] = $failedUpdate; } } }else{ if($row2["QUANTITY"] >= $row2["STORES"]){ for($i=0; $i<$row2["STORES"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertStore; } } }elseif($row2["QUANTITY"] < $row2["STORES"]){ for($i=0; $i<$row2["QUANTITY"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertQuantity; } } } }
Let's say customer 123 bought 4 of product A and they have 10 locations
customerNumber | product | category | startDate | expireDate | stores Because they purchased less than their store count, I insert 4 records. Now if my ```$validCheck``` query selects all 4 of those records (since they fall in a valid date range) and my loop sees that the array isn't empty, it knows it needs to update those or insert. Let's say they bought 15 this time. Then I would need to insert 6 records, and then update the expiration date of the other 9 records.
customerNumber | product | category | startDate | expireDate | stores There can only ever be a maximum of 10 (store count) records for that customer and product within the valid date range. As soon as the row count for that customer/product reaches the equivalent of stores, it needs to now go through and update equal to the quantity so now I'm running this but it's not running and no errors, but it just returns back to the command line $total = $row2['QUANTITY'] + $validCheck; if ($total < $row2['STORES']) { $insert_count = $row2['QUANTITY']; $update_count = 0; } else { $insert_count = $row2['STORES'] - $validCheck; // insert enough to fill all stores $update_count = ($total - $insert_count); // update remainder } for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $failedUpdate = "UPDATE_FAILED"; print_r($failedUpdate); $out[] = $failedUpdate; } } for($i=0; $i<$insert_count; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $failedInsertStore = "INSERT_STORE_FAILED!!!: " . $ex->getMessage(); print_r($failedInsertStore); $out[] = $failedInsertStore; } }```
I have 64 rows of players and want each User to be able to choose to bookmark an player, as well as unbookmark it too. I have a bookmark table set up, and each time a User decides to bookmark(+) or unbookmark(-) an player a row is created in the data table. (Matching the player ID and User ID) That's working fine. A query reads the most recent row for each player to determine if there is a + or - button next to each player. Testing the query and adding some dummy data, that part of it works too. However, the issue is the initial state, which I want to be a +. Once I go live, the table will be empty, nothing for the query to return/produce. How do I create an initial state of a + with no rows and have it not used or swapped out when Users start clicking + or -?
$query = "SELECT b.id, bookmark,playerID,userID,p.id FROM a_player_bookmark b LEFT JOIN a_players p ON '". $id ."' = playerID WHERE userID = '". $userID ."'&&'". $id ."' = playerID ORDER BY b.id desc LIMIT 1 "; $results = mysqli_query($con,$query); echo mysqli_error($con); while($row = mysqli_fetch_assoc($results)) { echo $row['bookmark']; if($row['bookmark'] == 0) { echo '-'; // this is where a form goes to remove a bookmark } else { echo '+'; // this is where a form goes to add a bookmark } } I tried to get it with CASE, but I don't think that's the right path. I also looked at UNION. I was able to get it to produce an initial state of +, but it still printed the already made up sample data too (so I have three instances of ++ or +-). (Players 2, 4 and 4)
Here is the what the UNION query looked like: $query = "(SELECT b.id, bookmark,playerID,userID,p.id FROM a_player_bookmark b LEFT JOIN a_players p ON '". $id ."' = playerID WHERE userID = '". $userID ."'&&'". $id ."' = playerID ORDER BY b.id desc LIMIT 1) UNION (SELECT b.id, bookmark,playerID,userID,p.id FROM a_player_bookmark b LEFT JOIN a_players p ON '". $id ."' = playerID WHERE userID = '". $userID ."' ORDER BY p.id desc LIMIT 1) ";
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 |