PHP - Trouble With Foreach?
I created an array using the array_diff function and it worked fine. My resulting array has lots of keys/values (like teamid, teamname, teamcity). I want to now display the teamid and teamcity as options in an HTML SELECT menu. I thought I would do something like this below, but it's only giving me the teamid (NOTE, I left out the Select tags because I'm good with that part of it ).
How do I write the code to get the teamcity to show as well? Obviously doing something very wrong Code: [Select] $remainingteams = array_diff($allteams, $chosenteams); foreach($remainingteams as $teamid => $value){ echo "<option>" . $teamid . "-" . $remainingteams['teamcity'] . "</option>"; } Similar TutorialsHi All, First time posting here. I've googled the problem, but can't seem to find a response that's the same. All I want to do is have a list of id numbers and for each id number in the array, submit a MySQL query to retrieve information relating to the id number. When I execute the code below however, I end up with only the last item in the array being printed in the echo statement. Any clues? Thanks, Code: [Select] // get array of ids $ids = getIDs($ids); // loop through input list foreach ($ids as &$id) { getVarDetails($id); } function getVarDetails($local) { $con = mysql_connect('localhost:3306', 'root', '********'); if (!$con) { die('Could not connect: ' . mysql_error()); } // set database as Ensembl mysql_select_db("Ensembl", $con); $result = mysql_query("SELECT * FROM variations WHERE name = '$local' LIMIT 1"); $row = mysql_fetch_array($result) while($row = mysql_fetch_array($result)) { echo $row['name'] . " " . $row['id']; echo "<br />"; } // close connection mysql_close($con); } This topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=355772.0 I'm not sure if the title explains it very well, but here is an image of it. I am trying to figure out how to access the option selected (equal, not equal, etc.), along with its input box, for each column (the checkboxes on the right) selected. The purpose of this is to allow a non-programming administrator user to create a custom query to access information. I can find out which checkboxes are selected no problem, but finding the accompanying drop-down option and input box is difficult for me. How do I do this? If you have a suggestion on how to change it, I'm very open. Thank you in advance! Code: [Select] if(!isset($_POST['submit'])) { echo " <form method='post'> <table> <tr> <td valign='top'>SELECT</td> <td valign='top'> <table>"; // LIST ALL COLUMNS IN A TABLE $result = mysql_query("SELECT * FROM table_name") or die(mysql_error()); $rowcount=mysql_num_rows($result); $y=mysql_num_fields($result); for ($x=0; $x<$y; $x++) { echo " <tr> <td> <input type='checkbox' name='fields[]' value='".mysql_field_name($result, $x)."'>".mysql_field_name($result, $x)." </td> </tr>"; } echo " </table> </td> <td valign='top'>FROM allocations</td> <td valign='top'>WHERE</td> <td> <table>"; // LIST ALL COLUMNS IN A TABLE $result = mysql_query("SELECT * FROM table_name") or die(mysql_error()); $rowcount=mysql_num_rows($result); $y=mysql_num_fields($result); for ($x=0; $x<$y; $x++) { echo " <tr> <td> <input type='checkbox' name='column[]' value='".mysql_field_name($result, $x)."'>".mysql_field_name($result, $x)." </td> <td> <select name='operator[]'> <option value='='>equals</option> <option value='<>'>does not equal</option> <option value='>'>greater than</option> <option value='<'>less than</option> <option value='>='>greater than or equal to</option> <option value='<='>less than or equal to</option> <option value='LIKE'>is like</option> </select> </td> <td><input type='text' name='criteria[]'></td> </tr>"; } echo " </table> </td> <td valign='top'><input type='submit' value='Process Query' name='submit' class='submit'></td> </tr> </table> </form>"; } else { echo "<b>Fields to edit:</b> "; foreach ($_POST['fields'] as $fields) { echo $fields,", "; } echo "<br><br>"; echo "<b>Columns to query:</b> "; foreach ($_POST['column'] as $columns) { echo $columns," HERE IS THE SPOT, "; } } public function update($data, $table, $where) { foreach ($data as $column => $value) { $sql = "UPDATE $table SET $column = $value WHERE $where"; print "table: ".$table." column: ".$column." whe ".$where; mysql_query($sql) or die(mysql_error()); } return true; } $data: $data = array( "username" => "Jack", "email" => "jack.gmail@gmail.com" ); $db->update($data, "users", 'id=1'); Working on this code that updates a column from a class. Everything is fine except for one issue. As of right now $column is set to "Jack" which outputs an error, instead of what it should be as "username". I'm sure it's something really simple, so any assistance is appreciated. Any ideas? Problem area is listed in red. Hi guys, Having a bit of trouble getting this to work. I should say before I start that im a rookie at PHP. Basically this is the code I have {counter start=0 print=false name=competcount} {foreach item=compet from=$person.competition} <img src="./bargraph/bar.php?value={$person.lineup[$compet.id].titular}&max={$club.matchsplayed[$compet.id].nummatchs}&info" /> The problem lies with the $club array not being defined Code: [Select] $club.matchsplayed[$competition.id].nummatchs How do I set up multiple arrays with foreach? Am I even in the right ball park with this? Hi can any one help please im still very new but hard trying The problem is that i only get 1 result back from the database i need it to loop any ideas please Code: [Select] $query = mysql_query("SELECT * FROM categorys, sub_categorys WHERE categorys.cat_id = sub_categorys.cat_id"); echo "<ul>"; $row[] = mysql_fetch_array($query); foreach($row as $category){ echo "<li>"; echo $category['category']; foreach($row as $sub_category){ if($category['cat_id'] == $sub_category["cat_id"]){ echo "<ul><li>".$sub_category["sub_category"]."</li></ul>"; } } echo "</li>"; } echo "</ul>"; I am trying to develop a calendar. I have code to determine the number of days for each month. I want to cycle through each day and spit out code for each day. Something like the following: Code: [Select] <?php $month = "December"; $days = 31; foreach($days){ echo "<div id='day_block'> ".$days." </div>"; } ?> i think i need to use a counter but don't know how, any help would be awesome! In the code I want to proceed to the next step only after stripslashes and strip_tags are completed. How do I put the code below with if? $stripped = array('name', 'location', 'bio'); foreach ( $_POST as $k => $v ) { if ( in_array($k, $stripped) ) { ${$k} = strip_tags($v); } } foreach ( $_POST as $p => $q ) { if ( in_array($p, $stripped) ) { ${$p} = stripslashes($q); } } Thanks, Ruth. why does wordpress is using foreach rather than while in listing records? common Code: [Select] while ($products = mysql_fetch_object($rs) { ... } but wordpress is using foreach Code: [Select] foreach ($posts as $post) { ... } which is better? because i'm trying to create my own code for database connection. today i programmed my own weight calculator. one thing i am having a problem is with trying to make it so if a weight is over a certain number, then the shipping price will increase by X. shipping prices are charged in 20000 gram blocks, so if I have something that is 22000 grams then that will be two blocks. what i need to do is something like (this is a big guess) Quote $row3 = 50; $weighttotal = 22000; if ($weighttotal > 20000) { foreach (20000) { $row3 += $row3;} } } } can it be done on php?? i have a table that echos 10 entries what i want to do is once it echos 5 records it starts a new table. I dont know how to go about this. Could you guys guide me the right way. Hi i am trying to pass values from a cart to a database using foreach. This is my code: Code: [Select] $columns = array('order_id', 'order_item_id', 'order_product_name', 'order_product_dimensions', 'order_product_options', 'order_product_quantity', 'order_product_price', 'order_product_subtotal', 'order_product_vat', 'order_product_delivery','order_product_total','order_product_sku','order_product_image_name','order_product_image_type','order_product_image_path','order_product_image_size','order_product_artwork_link','order_product_artwork_name','order_product_artwork_type','order_product_artwork_path','order_product_artwork_size','order_firstname','order_lastname','order_companyname','order_email','order_tel','order_billing_address','order_billing_address2','order_billing_town','order_billing_county','order_billing_postcode','order_shipping_address','order_shipping_address2','order_shipping_town','order_shipping_county','order_shipping_postcode','order_status','order_username'); $data = array_fill_keys($columns, 'NULL'); foreach($data as $key => $value) { $data[$key] = empty($_POST[$key]) ? 'NULL' : "'".mysql_escape_string($_POST[$key])."'"; $query = "INSERT INTO orders (id, order_created_at, ".implode(", ",$columns).") VALUES (null, NOW(), ".implode(",",$data).')'; } Problem is posting 2 or more products into the database. How do i split the values so it enters each product into the database? I'm trying to figure out why its saying Warning: Invalid argument supplied for foreach() in /home/content/y/a/n/yankeefaninkc/html/defiant/efedmanager/forms/booking.php on line 17. I thought I did the foreach loop right so far. $eventid = $_GET['id']; $query = "SELECT CONCAT_WS(' ', eventnames.eventname, events.label) AS event, DATE_FORMAT(events.bookingdate, '%M %d, %Y') AS bookingdate, events.nummatches AS nummatches FROM events, eventnames WHERE events.event_id = eventnames.id AND events.id = '" . $eventid . "'"; $result = mysqli_query ( $dbc, $query ); // Run The Query foreach ($nummatches as $matchnum) { echo "Match # $matchnum"; echo "<select class=dropdown name=matchtype id=matchtype title=Match Type>"; echo "<option value=0>- Select -</option>"; $query = 'SELECT id, matchtypename FROM matchtypes'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['matchtypename']."</option>\r"; } } I appear to be having a simple simon day! my foreach is only displaying the last result in the table as opposed to each row $num_rows = mysql_num_rows($query); echo "There are $num_rows records.<br>"; while($row = mysql_fetch_row($query)) foreach ($row as $field) { echo '<div class="results">'; echo $field; echo '<br></div>'; } And the source Code: [Select] <link href="../styles/clientbox.css" rel="stylesheet" type="text/css"> <body><br> <h3>My Services</h3> <div class="text"> You currently have the following services with us: </div> There are 2 records.<br><div class="results">test1<br></div> </body> </html> My table has 2 rows which the 1st one has a package of test and the second a package of test1 Can anyone help? Thanks Hi! When I echo $m below, it will show all selected options fine. Instead, I want it to show many I selected. So if I selected 3 in dropdown, I want it to say I selected 3 instead of showing their values. $allmaps=$_POST['maps']; foreach ($allmaps as $m) { echo 'm = '.$m.''; } <select name="maps[]" multiple>'.$maps.'</select> Hi All, I essentially am trying to figure out how to print out all of the zip codes that are associated with a search that I am doing, but not list the same zip code more than once. My current foreach statement is as follows and prints out the zip code for each property that is associated with the search: <ul> <?php foreach($properties as $property) { ?> <li><?=$property->$zipcode?></li> <?php } ?> </ul> How would I modify this to print out 1 occurrence of each zip code that is in the search, even if, for example 20 properties have the same zip code? Thanks in advance! P.S. - Tried using an array to work with it but pretty sure my logic was incorrect when putting it together and couldn't get past the errors. Anyways, thanks in advance for the help! Noob question. I've learned so much in the last couple of weeks that I've actually found two ways of doing the same thing! I was wondering which was the better method, if there is any difference. They are being used to print somewhere between 10 and 200 lines of text. Either: $categories_count= (count($categories[1])) -1; for ($u=0; $u < $categories_count; $u++) {echo "<li>".$categories[1][$u]."</li>";} Or: foreach ($categories[1] as $line => $cat) {echo "<li>".$cat."</li>";}; I'm trying to get a foreach loop to one variable that I can insert into MySQL - I've tried a number of things but can't get it working. How do I create one single variable that is created from the foreach? Thanks! Jason I have a form with radio buttons, depending on if a person selects yes, they will be given an answer after they hit submit. I don't want to do a bunch if un-necessary coding, so I'm trying something else, but it's not working. My form is this Code: [Select] <table width="100%" border="0" cellspacing="0" cellpadding="4"> <tr> <td align="center" valign="top">Yes</td> <td align="center" valign="top"><input type="radio" name="phone1" id="phone1" value="1" /></td> <td align="center" valign="top">No</td> <td align="center" valign="top"><input type="radio" name="phone1" id="phone1" value="2" /></td> </tr> </table> My code is this Code: [Select] <?php if(isset($_POST['submit'])) { $key; $key['phone1'] = "testing phone 1"; $key['phone2'] = "testing phone 2."; foreach( $_POST as $key => $value) { if($value == "1"){ echo $key."<br />"; } } } ?> Now, it does not show the wording associated with $key if the value is 1. Can anybody help me out here? This form is going to have over 100 questions. Thanks in advance. Hello i am trying to execute a linux program for every line of a textarea Code: [Select] $text = $_POST['links']; $text = htmlspecialchars($_POST['links']); $text = nl2br($text); foreach(explode("\n",$text) as $row) { $result = NULL; $command = 'the command'; exec($command,&$result); echo $result[0]."<br>"; } but this always print the result for last line of text area for example if there are 3 lines it print 2 blanks and 1 result... whats wrong?? |