PHP - While Loop Not Outputting Array As Expected
I am trying to load all rows from a table in a database into a table on a webpage. I cannot understand why the following code does not work:
Code: [Select] <?php ... echo "You are currently in a fleet. The details of the fleet are below.<br>"; $fleetName = $_SESSION['charFleetName']; $sqlFleetDetails = "SELECT * FROM `$fleetName`"; $queryFleetDetails = mysql_query($sqlFleetDetails); echo "<table>"; echo "<tr>"; echo "<th>Pilot</th>"; echo "<th>Ship</th>"; echo "<th>Type</th>"; echo "</tr>"; while($rowFleetDetails = mysql_fetch_array($queryFleetDetails)) { $charId = $rowFleetDetails['charId']; $charName = $rowFleetDetails['charName']; $shipHull = $rowFleetDetails['shipHull']; $shipType = $rowFleetDetails['shipType']; echo "<tr>"; echo "<td><a href=\"#\" onClick=\"CCPEVE.showInfo{1377, " . $charId . "}>" . $charName . "</a></td>"; echo "<td>" . $shipHull . "</td>"; if($shipType == 1) echo "<td>Logistics</td>"; if($shipType == 2) echo "<td>DPS Boat</td>"; if($shipType == 3) echo "<td>Sniper 120Km+</td>"; if($shipType == 4) echo "<td>Off-grid Booster</td>"; echo "</tr>"; } echo "</table><br>"; I originally had the $rowFleetDetails['charId'] and others in the echo instead of loading them into variables then echoing the variables but changed it to see if that was working, neither is. If I add an extra line outside of the while loop to echo the output of the array then the information is displayed fine, so I know that the information is being transferred from the table into the array correctly, but why is it not outputting properly in the While loop? Similar TutorialsI have only one result being displayed in a select query result whereas I'm expecting 4 results in an array. This is my code below. $sq2="SELECT course FROM course_reg WHERE userid=?"; $stm =$conn->prepare($sq2); $stm->bind_param("s",$logged); $stm->execute (); $return2= $stm->get_result(); $r2 = $return2->fetch_all(); //print_r($r2); foreach($r2 as $course){ foreach($course as $courses){ echo $courses; } }
If I do print_r($r2); it comes out with array containing all the possible results. When i loop through the array to get individual result, it only comes out with a single result. I.e CME211 I would be glad if you can help me figure where the issue is. Thanks!!!
hope to input the below data via $_POST into a while loop to preg_split by comma and then recursively create xml element tag with the various firstName lastName's and even separate further aliasFirstName aliasLastName's into an attribute field NAMES: firstName lastName [aliasFirstName aliasLastName], firstName lastName [aliasFirstName aliasLastName], firstName lastName [aliasFirstName aliasLastName], firstName lastName [aliasFirstName aliasLastName] $xml .= ' <element1 attribute="' . $_POST('AGE') . '">'; while ($row = ' . $_POST('NAMES') . ') { $row = preg_split('/[\s]*[,][\s]*/',' . $_POST["Actors"] . ',PREG_SPLIT_OFFSET_CAPTURE); $xml .= ' <element2> <NAME names="' . $_POST('NAMES') . '" alias="' . $_POST('NAMES') . '"></NAME> $xml .= ''; Hi, I'm having issues trying to add up the totals of each product type in a while loop- I'm sure it's straightforward to fix but for some reason I can't find a way to get it to add up all the totals of the various product types and list them so we have say 5 of product 1, 11 of product 2, 8 of product 3 and so on. So firstly the user searches between two different dates / times to get the orders made during that time period: (I'm using separare date and time fields as the datetime-local input doesn't work in a lot of browsers)
if($_POST['search']) //Now get the orders from the db $getorders = $oc_conn->query("SELECT * FROM oc_order WHERE date_added >= '$datetime1' AND date_added <= '$datetime2' AND order_status_id != 0 ORDER BY order_id DESC"); //Then generate start of a table in HTML, the while loop that follows will populate the rows while ($row = $getorders->fetch_assoc()) { //Get the order data
$firstname = $row["firstname"]; [/PHP] As mentioned in the comment above, what I need is the total $quantity of each $productname, across ALL orders in the time range, so that I can see how many of each product ($productname) were ordered in total. I tried using SUM for quantity in the mySQL, and COUNT for adding up the different product names but for some reason it didn't work. Can someone let me know what I need to do? Thanks :)
I am doing some study on using time() and date() and i just wrote this simple for loop to add one day to each iteration with +$i and its echoing the unix timestamp as opposed to the correctly formated date as it should be based on my code. Anyone have any idea why this is not working as expected? for($i=0; $i < 50; $i++) { echo $time = time()+$i . "<br />"; // add a day on each iteration echo date('y-m-d', $time) . "<br />"; // should echo 10-12-02, 10-12-03, 10-12-04, etc.. } what am i doing wrong here? arrgggg! maybe its too late for this s$%^#! Hey Guys. I crearted a class that goes loops through the session cart and displays the items. The problem that I am facing is when a return the values from a method it only brings back the first item that was added to the cart. It doesn't out out all the values.
However when I echo the the values straight from inside the method it shows all the items it looped through. I have tried every possibly thing to have all the items be displayed but I couldn't find to seem a solution.
Please note that I skipped a lot of the code in the example below for breviety. Such as instantiation, and other things. There maybe some syntax errors as well. I just did a breif copy and paste
Any help would be really appreciated!!!
class coreCartFunctions { protected function DisplayMenuItems($menu_item_id_session){ $qty_output = "<span style=\"font-size:18px\">X{$this->item_qty}</span>"; $this->menu_item_name = $this->getItems($this->menu_item_id,"menu_item_name"); if($this->DisplayPrice()){ $update_order_url ="item-detail.php?update_order=true&menu_item_id={$menu_item_id_session} &callback_url={$this->url}&store={$_SESSION['store_name']}"; $output = "<a class='{$this->menu_items_class_prop_a}' href='{$update_order_url}'> <div class='{$this->menu_items_class}'>{$qty_output} {$this->menu_item_name}</div>"; $output .= "<div class='menu_item_price'>\${$this->menu_item_price}</div></a>"; return $output; } else { $output = "<a class='{$this->menu_items_class_prop_a}' href='#'><div class='menu_item_name'>" .$qty_output." ".$this->menu_item_name ."</div></a>"; return $output; } } class displayCartItems extends coreCartFunctions { public function GetMenuItems() { foreach ($this->items as $menu_item_id_session) { //assign all the properties that belong to core class $output = $this->DisplayMenuItems($menu_item_id_session); return $output } } $display_items = $display_menu_item->GetMenuItems(); echo $display_items I have converted xml into an array with no problems, however I'm having difficulty outputting the various attributes. Here is a sample: Code: [Select] [0] => Array ( [@attributes] => Array ( [YourId] => 1082-1 [Name] => Woodwards Metals [Description] => ) ) The bit that is confusing me is the @attributes part. How would I output the 'Name' element for example? Hello, this is my first post here.
I am trying to output the rows of a certain query in sequence after a POST has been requested.
I have been successful in getting the output in a pure php file but when I try to implement this in a web page with html/css, I can't echo the array in arbitrary locations after the post has processed.
This is the code which outputs successfully in a pure php file, but I need it to work in a <textarea> field as the results of a search
$rows2 = array(); $rows3 = array(); while($stmt->fetch()){ $rows2[] = $stratoparse; $rows3[] = $date; } $search = array(); for($i=0;$i<=$num_rows;$i++){ echo $rows3[$i].' '.$rows2[$i].'<br>'.'<br>'; } }To further iterate what I am asking. When errors are stored, you write something like $errors['username']="A username is required.";Then in any location of a webpage I can call this or show it, provided by this <?php isset($errors['username']) ? $errors['username']:" ");?>That is the same thing I am trying to do with this array which can be an arbitrary count of rows... I have not been successful in getting this to work... I have been told of string concatenation... I don't know what to do Thank you for any help Here is my function which almost works as expected: <?php function find_value($array,$value) { for($i=1;$i<sizeof($array);$i++) { if($array[$i] == $value) { echo "$i . $array[$i]<br />"; return; } } } ?> And I call the function like so: <?php $names = array('Jason','Mike','Joe'); $name = 'Joe'; find_value($names,$name); ?> And the output is: 2 . Joe According to my understanding of Arrays, Joe would be index 3 BECAUSE my counter starts at 1 in my for loop??? Why is the result like this? What am I not understanding here? I have a Q&A Form/script where registered Users can share there thoughts on 10 Questions. On the backend I have these tables: member, answer, question Thanks to some help last night, I have been able to do a LEFT join and store the above data in a multi-dimensional array which always stoes the 10 Questions, and also any Answers that the User may have responded to. (Questions are optional.) I am having a hell of a time DISPLAYING this multi-dimensional array. The key is that I want my PHP and array to stay at the top of my script and use minimal PHP in my HTML section. Here is how I query the data and build my array... // ******************** // Build Q&A Query. * // ******************** // Build query. $q7 = "SELECT q.id, q.question_no, q.question_text, a.answer_text FROM bio_question AS q LEFT JOIN bio_answer AS a ON q.id=a.question_id AND a.member_id =? ORDER BY q.question_no"; // Prepare statement. $stmt7 = mysqli_prepare($dbc, $q7); // Bind variables to query. mysqli_stmt_bind_param($stmt7, 'i', $memberID); // Execute query. mysqli_stmt_execute($stmt7); // Store results. mysqli_stmt_store_result($stmt7); // Check # of Records Returned. if (mysqli_stmt_num_rows($stmt7) > 0){ // Questions Found. // Bind result-set to variable. mysqli_stmt_bind_result($stmt7, $questionID, $questionNo, $questionText, $answerText); // Populate PHP array with Questions & Answers. $x=1; while (mysqli_stmt_fetch($stmt7)){ $thoughtsArray[$x] = array('questionID' => $questionID, 'questionText' => $questionText, 'answerText' => $answerText); $x=$x+1; } echo '<pre>'; print_r($thoughtsArray); echo '</pre>'; // Close prepared statement. mysqli_stmt_close($stmt7); And in my HTML Form, here is how I am attempting to dynamically build the Q&A section... <form id="changeAnswers" action="" method="post"> <fieldset> <legend>Change Profile Answers</legend> <?php echo '<p>TEST: ' . $thoughtsArray[4]['answerText'] . '</p>'; foreach($thoughtsArray as $questionNo => $qaArray) { echo '<label for="question' . $questionNo . '">' . $questionNo . '.) ' . $qaArray['questionText'] . '</label>'; echo '<textarea id="question' . $questionNo . '" name="thoughtsArray[' . $questionNo . '][\'answerText\']" cols="60" rows="2">' . (isset($questionNo]) ? "htmlentities($thoughtsArray[$questionNo]['answerText'], ENT_QUOTES" : '') . '</textarea>'; } ?> I am able to retrieve and display the Questions from my multi-dimensional array as seen above, however, for the life of me, I cannot get the Input Fields (with any Answers) to work properly. I either get compile errors, or the code runs but my Input Fields are blank even when an Answer should be displayed?! I am hoping this is just a syntax and/or reference error. I'm still new to arrays, so properly retrieving an Answer from a multi-dimensional array is really tricky for me!! So close and yet so far away?! Can someone please help me out?? Thanks, Debbie Hello, Currently have an array like looks like the following when using print_r($session->items): Array ( [F1225] => 1 [EDS11147317] => 1 [1156D6RE001] => 1 [I111ADE47946] => 1 [S679AQ339] => 1 [S67914599] => 1 [CH111337631254] => 1 [S6787903647] => 1 [A11144O189] => 1 [F11144520] => 1 [121584Q12] => 1 [I11144661ADE] => 1 [S678829NB] => 1 ) I am trying to check if an item is in the array and if so, display a different result but currently every item says it is in the array when they are not (unless my logic is off...from the items I am looking at some should be included and some should not..but the below code is showing every item as having the same result). Example: foreach ($items as $item) { if (in_array($item->ItemID, $session->items)) { //$session->items is the array output above echo "In Array"; } else { echo "NOT in Array"; } } Currently everything say "In Array" when some should not. Am I using the in_array incorrectly? Thanks Everyone. I have a problem with the below code: Code: [Select] <?php $sql_ranks = ("SELECT vtp_members.id, vtp_members.name, vtp_members.teamleader, teams.team_name, count(vtp_tracking.id) surfs FROM vtp_members, vtp_tracking, teams WHERE vtp_members.team_id=".$_GET['t']." AND vtp_tracking.credit_members_id=vtp_members.id AND vtp_tracking.action_date > '$last_sunday' AND vtp_tracking.action_date < '$next_sunday' GROUP BY teams.team_name ORDER BY surfs DESC"); $rsranks = mysql_query($sql_ranks); echo "<br><table align='center' valign='top' border='0' width='300px'> <tr><td colspan='2' align='center'><font size='2px'><b>Team Rankings (Current Week)</b></font></td></tr> <tr><td><font size='2px'><b>Team</font></td><td align='right'><font size='2px'>Total Surfs</font></td></tr>"; while ($row = mysql_fetch_array($rsranks)) { echo "<tr><td><font size='2px'><b>".$row[team_name]."</font></td><td align='right'><font size='2px'>".$row[surfs]."</font></td></tr>";} echo "</table>"; ?> Problem is that the last output (".$row[surfs].") is the same for all teams. It seems it is not making a total of all id's and not per team_name. anyone can see what I am doing wrong. I need to sort by team_name and the surfs should display the total of the members with team_id is ".$_GET['t']." I have whiled my way through any number of forums and help pages so far. However, since I am not quite comfortable yet with PHP, I am not sure which option I have been given would be the right one. What I am trying to do: Create the source for a set of drop-down menus. The dropdown menu has columns, and then a H2 and P that go in each column, in varied numbers, so you have column1, h2 p; h2 p; h2 p column2, h2 p; h2 p etc....make sense? I am using an MySQL table as source so I can have a little CMS dashboard where I can change these and other values on the fly. So I have a MySQL table where I have a field that identifies the column (page name), and then values to fill the h2 and p tags. I.E.: page_name, content_title, content_text The idea, therefore, is to use PHP to figure out what the column names (that are repeated) in the mysql table and then create the dropdown based on the value in the subsidiary fields. Output is as a string in a variable value that is output via return (); My best estimation of how to do this is to use php to create a multidimensional array from the query result, where the first column is the page_name, followed by an array, the array being the remainder of the information. Based on information scrounged from other sources, I have come up with this so far: $query = "SELECT * FROM tbl_mainmenu WHERE mainmenu_type = '$mmtype'"; // what the query is $result = mysql_query ($query, $dbc); // connect to database and run query, setting the the result to dummy array variable '$result' // establish the multidimensional array $mmcontent_array = array (); //create the array where the values are content page and associated values in an array per each content page while ($result = mysql_fetch_assoc ()) { $page_name = $result['content_page']; $mmcontent_array['content_page'] = $result; } foreach ($mmContent_array[] as $key=>$value) { foreach () { $tmpelements[] = '<div class="col_2"><h2>' . $element[content_title] . "</h2>\n<p>" . $element[content_text] . "</p>\n</div>"; $elements = implode("\n",$tmpelements) . "\n" } $tmp[] = '<li><a href="#" class="drop">Products</a><!-- Begin Products Item -->\n<div class="dropdown_2columns"><!-- Begin 2 columns container -->' . $elements . 'whatever tags will close this') } Am I even in the ballpark? I am not sure which way to nest the foreach ()'s. The example I was working from used echo ()'s, and I am not sure if using $variable = implode () makes the task different. As a start, I am just wondering if I am creating the multidimensional array correctly? Hi all, I'm a first time poster here and I would really appreciate some guidance with my latest php challenge! I've spent the entire day googling and reading and to be honest I think I'm really over my head and need the assistance of someone experienced to advise the best way to go! I have a multi dimensional array that looks like (see below); the array is created by CodeIgniter's database library (the rows returned from a select query) but I think this is a generic PHP question as opposed to having anything to do with CI because it related to working with arrays. I'm wondering how I might go about searching the array below for the key problem_id and a value equal to a variable which I would provide. Then, when it finds an array with a the matching key and variable, it outputs the other values in that part of the array too. For example, using the sample data below. How would you recommend that I search the array for all the arrays that have the key problem_id and the value 3 and then have it output the value of the key problem_update_date and the value of the key problem_update_text. Then keep searching to find the next occurrence? Thanks in advance, as above, I've been searching really hard for the answer and believe i'm over my head! Output of print_r($updates); CI_DB_mysql_result Object ( [conn_id] => Resource id #30 [result_id] => Resource id #35 [result_array] => Array ( ) [result_object] => Array ( ) [current_row] => 0 [num_rows] => 5 [row_data] => ) Output of print_r($updates->result_array()); Array ( [0] => Array ( [problem_update_id] => 1 [problem_id] => 3 [problem_update_date] => 2010-10-01 [problem_update_text] => Some details about a paricular issue [problem_update_active] => 1 ) [1] => Array ( [problem_update_id] => 4 [problem_id] => 3 [problem_update_date] => 2010-10-01 [problem_update_text] => Another update about the problem with an ID of 3 [problem_update_active] => 1 ) [2] => Array ( [problem_update_id] => 5 [problem_id] => 4 [problem_update_date] => 2010-10-12 [problem_update_text] => An update about the problem with an ID of four [problem_update_active] => 1 ) [3] => Array ( [problem_update_id] => 6 [problem_id] => 4 [problem_update_date] => 2010-10-12 [problem_update_text] => An update about the problem with an ID of 6 [problem_update_active] => 1 ) [4] => Array ( [problem_update_id] => 7 [problem_id] => 3 [problem_update_date] => 2010-10-12 [problem_update_text] => Some new update about the problem with the ID of 3 [problem_update_active] => 1 ) ) How do i do if i've reached of array? i know i could do end of loop. but the array is present many times in my code. Code: [Select] while($row = mysql_fetch_assoc($getdetails)) { $people = $row['people']; $_SESSION['people'][] = $people; if(end($_SESSION['people'])) { //code } } i have an array in the loop but it isn't building up with results. i want it to check if the array exists, if not then create the array. Then in next loop it pushes a new value into the array. Below isn't working?... Code: [Select] while($row=mysql_fetch_assoc($get)); { $key = $row['keyword']; $scope= $_SESSION['scope']; if (!is_array($scope)) { $scopenew = array($key); $_SESSION['scope'] = $scopenew; } else { $scopenew = array_push($scope, $key); $_SESSION['scope'] = $scopenew; } } i have 2 arrays... first array of lastnames, second array of firstnames lastAry = array('smith', 'jones', 'reed', 'chan') firstAry = array('mary', 'chris', 'kim', joe', 'sara', 'tim', 'amy', 'fred') how do i loop through each lastnames and turn into a string with firstname so it looks like : smith | mary | chris jones | kim | joe reed | sara | tim chan | amy | fred Hi I am trying to tidy up a bit of php code to make the end display much better but I am a bit stuck, I have the following code which takes a mysql query and uses the result to create a google graph. <?php $str = ""; $str .= "<img src='http://chart.apis.google.com/chart?chs=600x300"; $str .= "&chd=t:"; $i=0; while($row_Recordset3 = mysql_fetch_assoc($Recordset3)){ $reading_array[$i] = $row_Recordset3['reading']; $date_array[$i] = date("j/n", strtotime($row_Recordset3['date'])); $i ++; } $count=0; $count = count($reading_array); if($count>1) { $rstring = implode(",", (array_reverse($reading_array))); $dstring = implode("|", (array_reverse($date_array))); }else{ echo $count; } $str = $str.$rstring; $str = $str."&cht=lc&chxl=0:|"; // We will close the src attribute with \' and to print escape character ' we shall precede it with \ $str = $str.$dstring; $str = $str."&chxt=x,y&chds=0,25&chxr=1,0,25,5&chm=o,0044FF,0,-1,8|b,3399CC44,0,1,0&chtt=Electricity Generation for the last 35 days'"; $str = $str." >"; //we shall echo the $str that will display the graph ?> <tr><td> <?php echo $str; ?> Currently the result is http://chart.apis.google.com/chart?chs=600x300&chd=t:10,6,1,11,12,7,6,2,1,1,4,10,1,5,12,3,3,6,1,6,3,3,1,5,3,1,1,6,8,5,8,8&cht=lc&chxl=0:|27/10|28/10|29/10|30/10|31/10|1/11|2/11|3/11|4/11|5/11|6/11|7/11|8/11|9/11|10/11|11/11|12/11|13/11|14/11|15/11|16/11|17/11|18/11|19/11|20/11|21/11|22/11|23/11|24/11|25/11|26/11|27/11&chxt=x,y&chds=0,25&chxr=1,0,25,5&chm=o,0044FF,0,-1,8|b,3399CC44,0,1,0&chtt=Electricity%20Generation%20for%20the%20last%2035%20days I need to make it display only every 7 dates so that they are readable but I still need the pipes in between to space out the dates correctly so they tie in with the correct point on the graph, like this where I manually removed some dates as a demo http://chart.apis.google.com/chart?chs=600x300&chd=t:10,6,1,11,12,7,6,2,1,1,4,10,1,5,12,3,3,6,1,6,3,3,1,5,3,1,1,6,8,5,8,8&cht=lc&chxl=0:|27/10|||||1/11|||||6/11|7/11|8/11|9/11|10/11|11/11|12/11|13/11|14/11|15/11|16/11|17/11|18/11|19/11|20/11|21/11|22/11|23/11|24/11|25/11|26/11|27/11&chxt=x,y&chds=0,25&chxr=1,0,25,5&chm=o,0044FF,0,-1,8|b,3399CC44,0,1,0&chtt=Electricity%20Generation%20for%20the%20last%2035%20days This is beyond my limited stills, can anyone help please? Thanks Gordon Code: [Select] // Get the users armour names $user_armour = array($user_head, $user_upper, $user_hands, $user_lower, $user_feet); $i=0; while($i < count($user_armour)) { $query1="SELECT * FROM armour WHERE id='$user_armour[$i]'"; $result1=mysql_query($query1); $array1=mysql_fetch_array($result1); $armour_name[$i]=$array1["name"]; $i++; } // set the users armours name $user_prot = array($user_head, $user_upper, $user_hands, $user_lower, $user_feet); // Get the users overall protection $i=0; while($i < count($user_prot)) { $query1="SELECT * FROM armour WHERE id='$user_prot[$i]'"; $result1=mysql_query($query1); $array1=mysql_fetch_array($result1); $armour_prot[$i]=$array1["protection"]; $i++; } // set the users protection $user_protection=$armour_prot[0] + $armour_prot[1] + $armour_prot[2] + $armour_prot[3] + $armour_prot[4]; Is there a way to get them as one so: Code: [Select] $user_armour = array($user_head, $user_upper, $user_hands, $user_lower, $user_feet); $i=0; while($i < count($user_armour)) { $query1="SELECT * FROM armour WHERE id='$user_armour[$i]'"; $result1=mysql_query($query1); $array1=mysql_fetch_array($result1); $armour_name[$i]=$array1["name"]; $armour_prot[$i]=$array1["protection"]; $i++; } // set the users armours name $user_prot = array($user_head, $user_upper, $user_hands, $user_lower, $user_feet); Will that work and if so how would you then get the 2 different values out of say "$user_prot[0]". Cheers guys, Ruddy I have following in a csv file: sku,quantity,price ---------------------- ML2225-1/4,10,38.77 ML2225-1/4,20,36 ML2225-1/4,30,33.23 ML2225-5/16,10,35.94 ML2225-5/16,20,33.37 ML2225-5/16,30,30.8 ML2225-3/8,10,34.37 ML2225-3/8,20,31.92 ML2225-3/8,30,29.46 ML2225-7/16,10,34.37 ML2225-7/16,20,31.92 ML2225-7/16,30,29.46 ML2225-1/2,10,34.37 ML2225-1/2,20,31.92 ML2225-1/2,30,29.46 ... I am able to read the file (fgetcsv). How do I build an array for each unique sku set, then do something, then continue to the next unique sku set? Thanks, Mike Hello, I'm trying to loop out the following value from the below array and cannot figure it out - orders.orderid Could anyone help me? stdClass Object ( [recsindb] => 4320 [recsonpage] => 10 [9] => stdClass Object ( [orders.orderid] => 83269442 ) [8] => stdClass Object ( [orders.orderid] => 83267681 ) )
echo "<pre>"; |