PHP - Simple(?) Question: Using Return In While Loop
Due to my home brewed templating system I must use 'return' instead of 'echo' or 'print'. I have a simple database query and running a while loop where all rows are to "printed" to the browser. But when I use return only the first row is shown.
Using echo will print out all of the rows as it should but of course it prints the rows outside of where they should in the template. This may be very simple but I am just starting out. I tried to use the forum's search to see if this has been answered but the daemon could not 'be reached' and searching on google brings up a ton of non-helpful links. The solution will be very helpful as I will be doing this A LOT in my scripts for my current project. Thank you! Similar TutorialsOk guys and gals I'm gettin' old! I know this is simple but I've spent way too much time on this now and am crying 'uncle'! I'm trying load a multi-dementional array with mysql_fetch_array results but I'm not getting it. Here's the rough basis for what I'm trying to do: $result = mysql_query("SELECT * FROM phpbb_profile_fields_data"); $row = mysql_fetch_array($result) or die(mysql_error()); $some_array = array( array( 'member_name' => $row['pf_firstname'] . " " . $row['pf_lastname'], 'member_title' => $row['pf_title'], 'member_employer' => $row['pf_employer'], ), array( 'member_name' => 'Janet', 'member_title' => '47', 'member_employer' => 'Husband', ), ); Okay, so that loads two $some_array elements with data. The first element has the first row of the database in question. Works fine but useless. So, with a "while ($row = mysql_fetch_array($result) )" what do I need to do to fill the $some_array with the query results? Thanks! Hi. I'm making a registration form, that will put each entered item into $_POST, which will then submit to the same page. First, I need to has the password with this method: Code: [Select] <?php public function hash_password($password) { $result = hash(sha512, $password . SALT); return $result; } >?then prepare the entered data for mysql with this method: Code: [Select] <?php public function query_prep($value) { $result = $this->real_escape_string($value); if (!$result) { die("Preparing query failed: " . $this->errno); } return $result; } ?> However, how can I "validate" the form. I need to pass the now prepared $_POST array into a loop, that executes the prepare method on each item in the array and then puts it in an array again. Also, how could I do some kind of function that checks if all required fields were filled, and how I can fail the submission if invalid characters were used. <?php function test(){ $x = ''; $arr = array('co'=>'color','ct'=>'design','cv'=>'weight','cm'=>'hight','cp'=>'price'); foreach($arr as $k=> $v){ $x .= '<tr><td> Td '.$k.' </td><td> Td '.$v.'</td></tr>' /* AFTER ACCESS THE ROW THAT DISPLAY "<tr><td> Td ct </td><td>Td design </td></tr>" */ /* insert HTML CODE (not by echo ) then complete the loop */ } return $x; } ?>
I have a form that I'm posting the contents to a 3rd party data management server via cURL. They return XML to let you know if the data was posted successfully or not. I'm trying to figure out how I can take that return XML and parse the data out of there. Quote <?php extract($_POST); $url = 'https://www.*domain*.com/DataReceiver'; $fields = array( blah blah blah ); foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } rtrim($fields_string,'&'); $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_POST,count($fields)); curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string); $result = curl_exec($ch); Now my question is, when the data posts and the XML is returned, how do I capture that? When I don't use cURL and post directly using HTTP POST, I get the XML returned at the exact same address I post to. So to process the XML returned, is this code correct? Quote $xml_feed_url = 'https://www.*domain*.com/DataReceiver'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $xml_feed_url); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $xml = curl_exec($ch); curl_close($ch); I'm kind of at a loss on what to do from this point... Thanks to anyone who takes the time to read and can help! Hey people! I've been setting a coding script for experience and this is my situation: To buy a virtual flower, one needs to have 50 virtual coins. So I first extract the number of coins the person has from the DB. If the user doesn't have the sufficient number of coins, the BUY button will not be available and vice versa. When the BUY button is clicked, I update the database, adding the flower to the user's inventory and subtracting 50 from the total number of coins the user has. This I do in that page itself using if(isset($_POST['submit'])) Now, I need to know how I could check whether the user has at least 50 coins even if the button is available. I hope that you could understand this. I want to do it for validation purposes. Its to prevent the user spending the coins he has in another browser window and then returning to the visible button to click it. I hope that I make sense. Thanks in advance! Regards, Thauwa Hi all, I have the following very simple for loop: $i=1; for ($i<26) { if (preg_match("~.~",$profile3["exp$i"])==1){echo $profile3["exp$i"],"<br />";} $i++; } However, it's not working and gives me the following error message: Parse error: parse error, expecting `';'' in ......... on line X where X is the line with " for ($i<26) ". Can somebody pls see where I've gone wrong? (prob a very stupid mistake, but I can't spot it) Thanks! I am trying to recursively pull records from a database to write to a csv. There are three test rows of data in my table (and no not including the table headers). The only issue is i can’t seem to get my for loop to display all the records – it only displays the last 2 rows so i’m very confused. Anyone suggest why this isn’t working? Code: [Select] $num_rows = mysql_num_rows($export); for ($i=0; $i <= $num_rows; $i++ ) { $row = mysql_fetch_row($export); echo $row[1] . $row[2] . $row[3] . $row[4] . $row[5] . $row[6] ."<br/>"; echo $i; } Incidentally the query is just a fetch all from datasbase. Anyone see where i'm going wrong? Thanks, drongo Hey all. I am a php newbie. Just starting to get my feet wet. So my issue is this. I have a MySQL database table called "blog" Within that table are "ID, photo_id, post_head, post_body" I have connected to the database via php and have been successfully echoing the fields onto my page. But the problem is that I don't know how to create a loop. I need it to show the latest post (biggest ID #) first then display descending down. Here is my code. As you can see I'm echoing the same variables and logically its displaying the SAME post 2 times. Any help would be just great! <table width="925" border="0" cellspacing="0" cellpadding="0"> <tr> <? $data = mysql_query("SELECT * FROM blog ORDER BY id DESC") or die(mysql_error()); while($info = mysql_fetch_array( $data )) { $id = $info['ID']; $photo_id = $info['photo_id']; $post_head = $info['post_head']; $post_body = $info['post_body']; } ?> <!-- POST 1 START --> <td width="180"> <img src="<? echo $photo_id ?>" /> </td> <td id="box_bg2" class="padding_state" width="275" valign="top"> <br /> <font id="post_head"> <? echo $post_head ?> </font> <br /> <font id="post_body"> <? echo $post_body ?> </font> </td> <td width="15"> </td> <!-- POST 2 START --> <td width="180"> <img src="<? echo $photo_id ?>" /> </td> <td id="box_bg2" class="padding_state" width="275" valign="top"> <br /> <font id="post_head"> <? echo $post_head ?> </font> <br /> <font id="post_body"> <? echo $post_body ?> </font> </td> </tr> </table> How would I add a loop to this PHP coding? I want to make it so that after 'I AM THOMAS' it will loopback to 'HELLO WORLD' and repeat the same cycle infinitely. Quote How do I make a loop for PHP? Is this right? <?PHP require ("config.php"); exec("mode com3: BAUD=9600 PARITY=n DATA=8 STOP=1 to=off dtr=off rts=off"); $fp =fopen("com3", "w"); while (true){ fwrite($fp,"HELLO WORLD"); fwrite($fp,"I AM THOMAS"); sleep(5); } fclose($fp); ?> Hey everyone, I have a database list of staff members that work at my office. I want to list each staff member with a while loop. In the database there is a field named "admin" where the value is either "y" or "n." I want to list administration first, then everyone else alphabetically by their last name. I wrote the code below that should work (haven't tested it yet) but I'm wondering if there is an easier, more efficient way to accomplish this. Thanks for any input that you may provide. Code: [Select] <?php $result1 = mysql_query("SELECT `prefix`,`lname`,`pos` FROM staff WHERE staffid > '0' AND admin == 'y' ORDER BY `lname` DESC"); $result2 = mysql_query("SELECT `prefix`,`lname`,`pos` FROM staff WHERE staffid > '0' AND admin == 'n' ORDER BY `lname` DESC"); while ($row1 = mysql_fetch_row($result1)) { $prefix = $row1[0]; $lname = $row1[1]; $pos = $row1[2]; $fullname1 = "$prefix $lname ($pos)"; echo "$fullname<br>"; } while ($row2 = mysql_fetch_row($result2)) { $prefix = $row2[0]; $lname = $row2[1]; $pos = $row2[2]; $fullname2 = "$prefix $lname ($pos)"; echo "$fullname2<br>"; } ?> Hi All, I'm jumping back into PHP and I have a basic loop question that I'm struggling with. I'm using a "date picker" code to select times during the day and then using a javascript to calculate the total hours for the day. However, I'm struggling with the loop to print out the fields. I need a loop that will print the following: first iteration: value = 1 value = 2 value = 0 second iteration: value = 2 value = 3 value = 1 The code I'm using is the following: Code: [Select] for ($id = 1; $id <=45 ; $id++) { ?> <?php if($id % 2) { ?> <div id="labor_template_day_100"> <input type="text" name="time1000<?php echo $id; ?>""/> <input type="text" name="time1000<?php echo $id+1; ?>" /> <?php } ?> <input type="hidden" id="emp<?php echo $id-1; ?>hours" value="0"/> <?php if($id % 2) { ?> </div> <?php } } This prints: first iteration: value = 1 value = 2 value = 0 Inserts just a hidden form field, then: value = 1 value = 2 value = 2 See below: Code: [Select] <div id="labor_template_day_100"> <input type="text" name="time10001" id="time10001" size="7" value="06:00 AM" onChange="CalcHrs('time10001', 'time10002', '0');"/> <input type="text" name="time10002" id="time10002" size="7" value="06:00 AM" onChange="CalcHrs('time10001', 'time10002', '0');" /> <input type="hidden" id="emp0hours" value="0"/> </div> <input type="hidden" id="emp1hours" value="0"/> <div id="labor_template_day_100"> <input type="text" name="time10003" id="time10003" size="7" value="06:00 AM" onChange="CalcHrs('time10003', 'time10004', '2');"/> <input type="text" name="time10004" id="time10004" size="7" value="06:00 AM" onChange="CalcHrs('time10003', 'time10004', '2');" /> <input type="hidden" id="emp2hours" value="0"/> </div> <input type="hidden" id="emp3hours" value="0"/> I have a feeling this is something basic I need to change. Hey guess I have a question about For Loops. I'm very new to php so please forgive anything stupid I am doing The follow code shows what I am trying to do with my for loop. It works great except that the $sizu value is spread out over all the fields. So instead of saying 150 in the first record set it prints 1 and then in the second record it prints 2 etc. Any idea what is causing this? If you need to see the rest of the code let me know I'm just trying to save bandwidth at first. for ($i=0; $i < count($var); $i++) { $quer = ("SELECT sbbx0, sbsizu FROM dwoshp WHERE sbfile = '$_POST[order]' and sbbrnu = '$_POST[location]' AND sbvaru = '$varu[$i]'"); $res = mysql_query($quer); while($r = mysql_fetch_array($res)) { $quant = $r['sbbx0']; $sizu = $r['sbsizu']; } $query_AddDots = "INSERT INTO tempresult(variety,grade,cont, quantity, size) VALUES ('$var[$i]', '$invgrade[$i]','TP','$quant', $sizu[$i])"; $AddDots = mysql_query($query_AddDots) or die(mysql_error()); } hello im having a little trouble getting what i want back from my loop. on my page i have 2 placeholders. each placeholder needs to pull the element id from the db that belong in that placeholder so in the db i have these columns: id = (the placeholder id) number = (the placeholder number) element. = (the element id) for example: place holder 1 has element_id 1 & 2 place holder 2 has element_id 1 & 3 id - number - element_id 1 - 1 - 1 2 - 1 - 2 3 - 2 - 1 4 - 2 - 3 in the places holder if have: Code: [Select] //place holder 1 $phNo = "1"; $holder = Placeholders::find_by_phID($phNo); //place holder 2 $phNo = "2"; $holder = Placeholders::find_by_phID($phNo); this is the class code: - I MIGHT BE DOING THIS WRONG Code: [Select] public function find_by_phID($phNo=0){ $sql = "SELECT * FROM ".self::$table_name." WHERE number=".$phNo.""; $result_array = self::find_by_sql($sql); return !empty($result_array) ? array_shift($result_array) : false; } THIS IS WHAT I TRIED: inside the placeholder i put a loop: Code: [Select] <?php $phNo = "1"; $holder = Placeholders::find_by_phID($phNo); foreach ($holder as $holders){ echo "Elements id = ".$holder->contElements_id."<br />"; } echo "<br/>"; ?> but the retults are all wrong. it comes back with: Quote Elements id = 5 Elements id = 5 Elements id = 5 Elements id = 5 Elements id = 5 Elements id = 5 Elements id = 5 what placeholder 1 should come back with is just element id 1 & 2 Quote Elements id = 1 Elements id = 2 any thoughts thanks rick I was wondering if you loop through an array and in the foreach() you specify an if statement that unsets certain items from the array, if those get unset from the original loop. Probably doesn't make much sense so heres an example Code: [Select] <?php //say there are 3 items in the $parent array //say there are 10 items in the $items array //say only the second item in the $items array value_one equals "abcd" foreach($parent as $id => $value) { foreach($items as $key => $value) { if($items[$key]['value_one'] == "abcd") { unset($items[$key]); } } } ?> So on the first item in the parent array, all 10 items would be cycled through. On the second second item of the parent array, all 10 items would be cycled through and the one item that has value_one == "abcd" would be unset. So on the third item of the parent array, am i correct in assuming only 9 items would be cycled through because there would be only 9 items in the $items array? hello. i have a foreach loop thats pulling out information that i dont want. how do i stop it. this is the loop Code: [Select] //GET THE TEXT $PCa = PageContent::find_by_pageContID($PCidA); foreach ($PCa as $PCas){ $title = $PCas->title; $link = $PCas->link; echo $title; echo "<br/>"; } the loop sits inside this function which has more loops Code: [Select] function listNavText($PHGlidA, $PHLobA, $PHLodA){ //GET THE LANGUAGE $langBS = basicSettings::find_by_id(1); $langID = $langBS->language_id; //GET THE LIST ORDER $PHLoa = PhLists::find_by_order($PHGlidA, $PHLobA, $PHLodA); foreach ($PHLoa as $PHLoas){ $PHLidA = $PHLoas->id; //GET THE LIST TEXT IDS $PCba = PCbridge::find_by_list($PHLidA, $langID); foreach ($PCba as $PCbas){ echo $PCidA = $PCbas->pageContent_id; //GET THE TEXT $PCa = PageContent::find_by_pageContID($PCidA); foreach ($PCa as $PCas){ $title = $PCas->title; $link = $PCas->link; echo $title; echo "<br/>"; } } } } this is what it echoes out 105L1-Title1 118 116 114 112 110 108L2-Title4 111 109L2-Title5 113 115 117 106L1-Title2 119 107L1-Title3 the number at the start is the text id L1-Title1 to L1-Title5 are tiles ($title) the spaces are links ($links) the problem is that i don't want the link spaces showing. just the 5 titles thanks Hi i am in a situation where i need to use two tables. please look at my code $result= $db->dbrun('select * from table_user'); while($row = mysql_fetch_array($result)): echo $row['username'] . '<br />'; endwhile; now my problem is i wants to get something from other table where user id match with $row['id'], $result= $db->dbrun('select * from table_user'); while($row = mysql_fetch_array($result)): $query= $db->dbrun('select id from table_other where user_id =$row['id']'); while($user_row = mysql_fetch_array($query)): echo $row['username'] . ' - ' . $user_row['id'] . '<br />'; endwhile; endwhile; so my main question is is it ok to run $query within a while loop because i cant run this query without $row['id'] which i gets after loop started or is there any other good way. Thanks for answering. Hi guys. I am new here but have been following the board for about a month. I will try to contribute as much as possible. I was given a problem, and need some help out with it. Most of you will probably find it pretty simple. Here is what I have: ?> //Rewrite the while loop using a for loop. for echo "8 times $num is: " . ($num*. "<br/>" } /* For the output I need: 8 times 1 is:8 8 times 2 is:16 8 times 3 is: 24 8 times 4 is:32 8 times 5 is:40 8 times 6 is: 48 8 times 7 is: 56 8 times 8 is:64 8 times 9 is: 72 8 times 10 is: 80 */ ?> So basically I need to fill in that missing code(rewrite the while loop using a for loop) Thank you so much in advance! I have a script that displays a certain result set, the row I am concerned about is called 'endonum'. Some rows will have the same number in this field. Is there a way to only show 1 result with the same number in this field. The array will be like '1, 2, 3, 3, 4, 4, 4, 4, 5, 5, 5' and so on, but I just want to display 1 of them, not all. Kinda confusing but maybe someone gets it. Here is the code. <?php $selectendo = mysql_query("SELECT * FROM endorse WHERE agency = '$agency' AND finalized = 'No'")or die(mysql_error()); while($showendo = mysql_fetch_array($selectendo)) { $endonumber = $showendo['endonum']; ?> <li><a href="viewendo.php?endonum=<?php echo $endonumber;?>">Endorsement Number:<?php echo $endonumber . " Date: " . $showendo['date'];?></a></li> <?php } ?> Hello Guys, I have a question. I have the following code to grab all of my $_POST vars and run through my filter function Code: [Select] foreach($_POST as $key => $value) { $mydata[$key] = filter($value); } Before using the foreach loop I was just doing the basic $var1 = $_POST['var1']; $var2 = $_POST['var2']; I'm going to have about 40 - 50 $_POST vars so my question is how do i return it as just a $var name instead of having to do this echo "<br><br><br>example1" . $mydata['var1']; echo "<br><br><br>example2" . $mydata['var2']; I guess its hard for me to explain.. Thanks for your help! This is more of a technical question that i could not find the answer to pn the php.net manual pages. take the folowing example code: foreach ($array as $key => $value){ $tempvariable = some_property_of($value); } unset($tempvariable); is that unset statement needed? Does PHP automatically destroy the variables once the foreach loop is left? |