PHP - Foreach But Random?
I want to loop through all the values of an array.. but each time, JUST FOR THE LOOP, i want to go through the array values randomly.
How do you suggest I do this? Similar TutorialsThis topic has been moved to Application Frameworks. http://www.phpfreaks.com/forums/index.php?topic=355772.0 As above, I have a lottery style site that picks a random number between 1-8 but my users complain for some reason that this is not enough. So i was told to look into using fopen and random.org to generate a random number. Anyone have experience of this and perhaps a code snippet for me to look at and possibly use? help will be appreciated. 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, "; } } 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? 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. 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 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. 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? 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. 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> 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 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 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! 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 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>"; 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>";}; Hi, I am new to php, mysql and have made some progress, but recently ran into a wall. I hope someone can help me. I am building a simple links script that has categories and a list of links with website name, url and a brief description. I have two tables-categories and links. I have gotten the back end finished and can add, edit and delete links and categories. The problem is in the front end. I have the script set up so that when I click on a category name a page is dynamically created using ?id=idnumber. and the category name is echoed on the page. But I can't seem to find the solution I need to get the links that have a matching category name to display. I have tried using JOIN, LEFT JOIN, INNER JOIN, and RIGHT JOIN and get the same result, ALL the links in the links table are displayed. I think I need to create a new array and use the foreach loop to accomplish this, but I am not sure. Nor am I sure how to use the foreach even though I have read several tutorials on it. Here is the code I have so far. Any help would be appreciated. Thanks in advance. Code: [Select] <? include "db.php" ?> <?php $id = intval($_GET['id']); // force user input to an int if(!empty($id)) // if the user input is not empty or 0 { $query = "SELECT * FROM categories WHERE id = $id LIMIT 1"; // attempt to select the row for the given id $result = mysql_query($query) or die(mysql_error()); if(mysql_num_rows($result) > 0) // if the categorie was found { $row = mysql_fetch_assoc($result); // fetch the resultset to an array called $row echo $row['categories']; // echo the categories field from the row // etc. } else { die('Error: Bad ID'); // the categories was not found } } else { die('Error: Bad ID'); // the id given was not valid } mysql_close(); ?> <? include "db.php" ?> <?php $sql="SELECT * FROM links,categories ORDER BY links.categories LIMIT 10"; $result=mysql_query($sql); ?> <table width="80%" align="center" border="0" cellspacing="1" cellpadding="0"> <tr> <td> <table width="100%" border="1" cellspacing="0" cellpadding="3"> <tr> <td colspan="3"><strong>List data from mysql </strong> </td> </tr> <tr> <td align="center"><strong>Name</strong></td> <td align="center"><strong>URL</strong></td> <td align="center"><strong>Content</strong></td> </tr> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td><? echo $rows['name']; ?></td> <td><a href="<? echo $rows['url']; ?>"><? echo $rows['url']; ?></a></td> <td><? echo $rows['content']; ?></td> </tr> <?php } ?> </table> </td> </tr> </table> <?php mysql_close(); ?> Does anybody know how to make the following code correct? real sorry but its just absolutely blowing my mind im awful with loops and have pretty much no clue what the hell im doing in honesty, any help would be great, Thanks Code: [Select] $addIDs_ary = array_map('intval', $_POST['chkInv']); $addIDs_ary = array_filter($addIDs_ary); $value = $addIDs_ary; //Check if hit_id is already in hitlist $query = mysql_query("SELECT * FROM hitlist WHERE player_id = '$playerID'"); $result = mysql_query($query); while ($result = mysql_fetch_assoc($result)) foreach ($result as $hit_id => $value){ if($result[$hit_id] == $value); $str = ""; } } else hi friends! this code Code: [Select] foreach ( $users as $key => $value ) { $user_ids = implode(',', $value); echo "$key - $user_ids<br />"; } sends this output: Code: [Select] user one - 376,373 user charlie - user beta - 372 I need the $user_ids are shown in a DropDownList, of course only if the $user_ids is not empty. How can I do? thanks! |