PHP - Randomly Select An Item
Hi,
I have an array of items and I randomly want to remove one from the array. What's the easiest way to go about this? Similar TutorialsI am working on a quiz app image 1 shows the index.php page image 2 shows the first question image 3 shows the second question image 4 shows the third question image 5 shows the result after completing the quiz image 6 shows the database 'quizzer' and its tables image 7 shows the 'questions' table image 8 shows the 'choices' table THIS LINK CONTAIN ALL THE CODE (and images) I HAVE DONE SO FAR https://www.mediafir...o7f5q0fe6y/quiz 1.Now my question is how to select the question RANDOMLY from 'questions' table along with 'choices' (by adding code to the existing file or create a new one). 2.If user refresh/reload the page before starting ('Start Quiz') or click 'Take Again' after finishing the quiz, the question should appear randomly. 3.Basically I want to change the order of question appearing in the browser each time I refresh. 4.My work so far is mentioned above.........Please help me with this "RANDOM" problem !! P.S - Will it be possible, by creating a random function in PHP which will check for repeat questions in a session and check for the 'id' of the question and if it is new display it on the page. If so what should I do and if no then how to do? Say I have two variables like below. I basically want to select one of them, but through random choice. How do I do that? $orange = 'Orange'; $apple = 'Apple';
I am unsure of how to select something made up of a composite key. Allow me describe the entity... Event ShowID (pk) VenueID (pk) StartDateTime (pk) My Checkout process will have an HTML Table displaying maybe 3-4 different Events like this... Code: [Select] ========================= Register in 3 Easy Steps... Step #1: Select a Date and Attendees Event Ticket (Update) Choose Name Cost Attendees Total One Flower Show $20 ___ $0 <<Buy a Ticket>> Mankato, MN Sept 24, 2011 Flower Show $20 _3_ $60 <<Buy a Ticket>> Willmar, MN Oct 1, 2011 Banjo Jamboree $50 ___ $0 <<Buy a Ticket>> Brainerd, MN Oct 8, 2011 ========================= When a User clicks on a particular "Buy a Ticket" button, how do I capture the 3 Composite Key Values I need so I can insert them into my Order table? Maybe a better question to ask, is HOW/WHERE would I store the 3 Composite Key Values so that when a User clicks on a given "Buy a Ticket" button, that I have the values I need to build my Order record?? Normally with just one value (e.g. Drop-Down List), when someone selects a value, there is a corresponding code that you'd use. For example "Extra Large" in a Drop-Down List equals "3". Hope I'm making sense?! Thanks, Debbie In my php site i have a select button.On selecting an item from the select box ,the corresponding picture should be displayed in the <img>,from the mysql database. This is not happening with the following code <form name='abc' method='post'> <select name="std_name" onChange="this.form.submit();"> <option value="...Select...">...Select...</option> <option value="Adam">Adam </option> <option value="Amanda">Amanda</option> <option value="Angel">Angel </option> <option value="Brewier">Brewier</option> <option value="Butle">Butler </option> <option value="Carrie">Carrie </option> </select><br /> <?php if(isset($_POST['submit'])) { $aname1=$_POST['std_name']; $sql1="select * from std where name='$aname1'"; $result=mysql_query($sql1); while($n=mysql_fetch_row($result)) { echo $n[2]; echo "<img src='$n[2]' width='118' height='133' name='std/>";} } ?> <img src="Adam.jpg" width="118" height="133" name="std"/><br /> </form> This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=354366.0 I have a script that seems to work well to insert a bookmark into a users database when he/she is logged into the system but I am having a hard time figuring out how I would go about making a work-a-round for having an item selected before being logged in, and inserted after they have logged in or registered. For example, I would like a user to be able to select an Item to add to bookmark whether that user is logged in/registered or not and if they are not, they would be greeted with a login/registration form and after successful login the add bookmark script would be initiated on the item previously selected. What I've got this far: Simple form to add bookmark: <form name="bm_table" action="add_bms.php" method="post"> <input type="text" name="new_url" value="http://" /> <input type="submit" value="Add Bookmark"/> </form> Then I have the add bookmark script: BEGIN php $new_url = $_POST['new_url']; try { check_valid_user(); //cannot get past this part since it ends the script....code below if (!filled_out($_POST)) { throw new Exception('Form not completely filled out.'); } // check URL format if (strstr($new_url, 'http://') === false) { $new_url = 'http://'.$new_url; } // check URL is valid if (!(@fopen($new_url, 'r'))) { throw new Exception('Not a valid URL.'); } // try to add bm add_bm($new_url); echo 'Bookmark added.'; // get the bookmarks this user has saved if ($url_array = get_user_urls($_SESSION['valid_user'])) { display_user_urls($url_array); } } catch (Exception $e) { echo $e->getMessage(); } END php Checking valid user - the portion I cannot get past in the above script: function check_valid_user() { // see if somebody is logged in and notify them if not if (isset($_SESSION['valid_user'])) { echo "Logged in as ".$_SESSION['valid_user'].".<br />"; } else { // they are not logged in do_html_heading('Problem:'); echo 'You are not logged in.<br />'; do_html_url('login.php', 'Login'); do_html_footer(); exit; } } How would I go about modifying the script so that a user could fill in the form (later it would be a link...obviously they probably wouldn't be filling in a form that is log-in specific - but same concept I think) Thanks in advance for the help! tec4 Hi there, I think this is a big question but I'd appretiate any help you can provide!! I have a list of items and subitems in a table that looks like this: id parent_id title 1 0 House Chores 2 1 Take Out Trash 3 1 Clean Room 4 0 Grocery List 5 4 Eggs 6 4 Produce 7 6 Lettuce 8 6 Tomato 9 4 Milk I want to display it like this: (+) House Chores: > Take Out Trash > Clean Room (+) Grocery List: > Eggs (+) Produce > Letutce > Tomato > Milk So basically each entry in the table has an unique id and also a parent id if it's nested inside another item. I "sort of" got it figured out in one way, but it doesnt really allow for nested subgroups. I'd like to know how would y'all PHP freaks to this Also taking suggestions for the javascript code to expand/collapse the tree !! Thank you! Well I am looking to change this url Code: [Select] http://website.com/product.php?Item=2369 to Code: [Select] http://website.com/product.php?Item=Item-Name Heres a snip of the code that handles that. <?php include_once('mysql_connect.php');$id = (int)$_GET['Item'];?>() any help would be appreciated. Hello all I have a form for a meeting unable to attend log. An attendee calls in to say they will not be able to make meeting and the form saves the reason etc into a db and infroms (via emails) all staff members who would have attended of the cancelation. It works but for some reason the record saves twice in the db on occasion and I'm unsure why. The loggers fills in some deatils on a form called log.php and then clicks save which goes to the following page: Code: [Select] <?php $auth = $_COOKIE['auth']; $login_id = $_COOKIE['login_id']; header("Cache-Control:no-cache"); if(!$auth == "ok") { header("Location:../log_index.php"); exit(); } include("../php_include/connection.php"); include("../php_include/functions.php"); $absent_date = $_POST['absent_date']; $call_time = $_POST['hour'] .":". $_POST['mins']; $reason = (! get_magic_quotes_gpc ()) ? addslashes ($_POST['reason']) : $_POST['reason']; $reason = fix_quotes($reason); $log_date = date ("d/m/Y"); $log_time = date("G:i"); $attendee_id = str_replace("\'","'",$_POST['attendee_id']); $attendee_name = str_replace("\'","'",$_POST['attendee_name']); $attendee_email = str_replace("\'","'",$_POST['attendee_email']); $sent = $_POST['sent']; if( !$sent ) { echo( "Error - Data not sent from main form.<br><form action=\"log.php\"><input type=\"submit\" name=\"back\" value=\"Back\"></form>" ); } else { $sql = "SELECT staff_username FROM appointments where attendee_id = \"$attendee_id\" and date = \"absent_date\" "; $rs = mssql_query( $sql, $conn ) or die( "Please contact admin and quote: Could not execute Find Staff Query" ); if(mssql_num_rows($rs)!=0) { while ($row = mssql_fetch_array($rs)) { $staff_email = $row["staff_username"]. "@ourdomain.co.uk,"; $to_staff .= $staff_email; } $re_staff = "Unable to attend appointment logged for $attendee_name ($attendee_id)"; $msg_staff = "An unable to attend appointment has been logged for $attendee_name ($attendee_id) \n\nReason: $reason \n\nDate of Absence: $absent_date \n\nTime of Call: $call_time \n\nLog Date: $log_date \n\nLog Time: $log_time \n\nLogger: $login_id \n\nThank You"; $headers_staff = "From: No-Reply@ourdomain.co.uk \r\n"; if( mail( $to_staff, $re_staff, $msg_staff, $headers_staff ) ) { $sql2 = "insert into att_log (attendee_id, reason, absent_date, call_time, log_date, log_time, logger) values (\"$attendee_id\", \"$reason\", \"$absent_date\", \"$call_time\", \"$log_date\", \"$log_time\", \"$login_id\") "; $rs2 = mssql_query( $sql2, $conn ) or die( "Please contact admin and quote: Could not execute Save Absence Log"); $re = "Absence logged for you - $attendee_name ($attendee_id)"; $msg = "An absence has been logged for you - $attendee_name ($attendee_id) \n\nReason: $reason \n\nDate of Absence: $absent_date \n\nTime of Call: $call_time \n\nLog Date: $log_date \n\nLog Time: $log_time \n\nLogger: $login_id \n\nThank You"; $headers = "From: No-Reply@ourdomain.co.uk \r\n"; if( mail( $attendee_email, $re, $msg, $headers ) ) { $sent_to = str_replace(",",",<br>",$to_staff); echo("Thank you, An email has been sent to the attendees meeting organisers<br><br>$sent_to<br>as notification of this absence.<br><br>An email confirming this absence has been sent to the attendees email account.<br><form action=\"log.php\"><input type=\"submit\" name=\"back\" value=\"Back\"></form>"); } else { echo("Error.....Email not sent to attendee.<br>This may be because the attendee did not provide an email account.<br>Please go back and check the record has been saved.<br><form action=\"log.php\"><input type=\"submit\" name=\"back\" value=\"Back\"></form>"); } } else { echo("Error.....Email not sent and record not saved.<br>This may be because the Email server is not responding. Please go back and try again.<br>If the problem persists please contact Admin.<br><form action=\"log.php\"><input type=\"submit\" name=\"back\" value=\"Back\"></form>"); } } else { echo("<br><br>Error.....Email not sent and record not saved.<br><br>This may be because the there is no record of a meeting for this Attendee.<br>Please contact Admin with the Attendee ID: ".attendee_id."<br><br><form action=\"log.php\"><input type=\"submit\" name=\"back\" value=\"Back\"></form>"); } } include("../php_include/close_all.php"); ?> Can anyone shed some light? Or suggest code improvements? Many Thanks I am having an issue in which fopen randomly generates either timeout or "failed to open stream" errors when trying to get stock quotes from yahoo finance. Here's an example. <b>Warning</b>: fopen(http://finance.yahoo.com/d/quotes.csv?s=NFLX&f=sl1d1t1c1ohgv&e=.csv) [<a href='function.fopen'>function.fopen</a>]: failed to open stream: HTTP request failed! This issue occurs sporadically; sometimes it's fine, other times it errors out causing the quote to fail. Any ideas on how I can resolve this? Thanks very much. 15 rows selected from the table. I want to randomly display an ad between them. Here's the code: Code: [Select] $count = 1; (mysql select rows) $number = rand (1,15); if ($count == $number) { echo 'ad code '; } $count++; I want the ad to be displayed only once and in the above code, depending on the generated number by rand() matching the $number the ads will be displayed more times. How can I limit this only to one? If I have an array, $array, how can I loop through it (e.g. with a foreach() ) .. but just do it randomly? So each time, random entries of the array are used and not necessarily in order. I have retrieved 5 values from a database table... The table is such as-> tmeta_id team_id 1 1 2 2 3 3 4 4 5 5 Code: [Select] Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) .. and this array I have named $nonrandom_teamno. using shuffle() I have rearranged the array, the new array being $random_teamno, which is such as the following-> Code: [Select] Array ( [0] => 3 [1] => 4 [2] => 5 [3] => 2 [4] => 1 )I am having real problems reinserting this into the SQL tables... I have been trying the foreach loop below... Code: [Select] for($i = 1; $i < (count($nonrandom_teamno)+1); $i++) { $db->query("UPDATE ancl_teammeta SET team_id ='$random_teamno[$i]' WHERE tmeta_id='$nonrandom_teamno[$i]'"); }It puts numbers back in the database, but not random ones. Please help me with the correct query I need!! Thank you.. I need a simple code like Code: [Select] $test1="1"; $test2="2"; $test=$test1|$test2; echo $test;to randomly catch the value of strings $test1 or $test2; as each time running the code, echo shows randomly one of the strings. Could you please guide what the third line should be ? I'm trying to write code that will let me pull 10 out of 15 images out of a folder and display them on my site. The images are all different, and I don't want dupes to show. So far, I have the following code figured out: --------------- $s = array ("image.jpg", "image2.jpg"); // as many images as you want $n = rand(1,len($s)); // randomly pick a number between 1 and the length of the array echo "<img src='". $s[$n] .'">"; // create an image tag for the randomly selected imagine (value of the randomly defined key) array_pop($s, $n); // This piece isn't right, it needs to EXTRACT and delete the $n array element. // Next random image $n = rand(1,len($s)); echo "<img src='". $s[$n] .'">"; --------------- Any ideas what array_pop should be to work properly? Thank you for the help! Hi there, I'd be ever so greatful if someone could help me please. I'm really trying to get my head around working with arrays and could really do with an example in a context i fully understand. I have made a test page for this and made a query that will search for appropriate records in my database: Code: [Select] <?php $colname_Class = "3"; $colname_Ships = "-1"; if (isset($_SESSION['MM_Username'])) { $colname_Ships = (get_magic_quotes_gpc()) ? $_SESSION['MM_Username'] : addslashes($_SESSION['MM_Username']); } mysql_select_db($database_swb, $swb); $query_Ships = sprintf("SELECT * FROM ships WHERE PlayerName = %s AND Class=%s AND Template='1'", GetSQLValueString($colname_Ships, "text"), GetSQLValueString($colname_Class, "int")); $Ships = mysql_query($query_Ships, $swb) or die(mysql_error()); $row_Ships = mysql_fetch_assoc($Ships); $totalRows_Ships = mysql_num_rows($Ships); echo $row_Ships['ShipID']; echo ' '; echo $row_Ships['ShipName']; echo ' '; echo $row_Ships['Class']; echo ' '; echo ' '; echo $totalRows_Ships = mysql_num_rows($Ships); ?> After i made the query i echo out the ShipID, ShipName and Class from the queey which displays: 5 New Ship 3 1 So you can see the ShipID = 5, the name of the Ship is New Ship, its Class is 3 and there is only 1 record found in the database that matches the search criteria. Lets say there are 10 records in my database... What i really need to do is make an array of the outputted results, determine the number of records and then to randomly choose 1 of the results from the array. Can you help me please?? If i can see an example in this context i feel i'd really learn something here. If you can help, please do because im well stuck. Thank you Tom Hi, I'm trying to invert a random section of an image. The only way I've thought of doing this in PHP, is to split the image up into sections using imagecopyresampled then negate one of the sections using the imagefilter IMG_FILTER_NEGATE. Then put them all back together using imagecopymerge. Now I have managed to get this working when negating the first section ($split_first), but whenever I try to negate any other section (e.g. $split_sec) nothing happens. Now I know my code doesn't randomly invert it, I'm just trying to get it to work for each section first then I'll try get that working. Below I have posted my code. Any help would be be appreciated, Thank you in advance! <?php $image=imagecreate(400, 100); $red = imagecolorallocate($image, 255, 0, 0); imagefill($image, 0, 0, $red); $split_first=imagecreate(100, 100); $split_sec=imagecreate(100, 100); $split_thir=imagecreate(100, 100); $split_four=imagecreate(100, 100); imagecopyresampled($split_first,$image,0,0,0, 0,100,100,100,100); imagecopyresampled($split_sec,$image,100,0,100,0,100,100,100,100); imagecopyresampled($split_thir,$image,200,0,200,0,100,100,100,100); imagecopyresampled($split_four,$image,300,0,300,0,100,100,100,100); imagefilter($split_sec, IMG_FILTER_NEGATE); imagecopymerge($image,$split_first,0,0,0,0,100,100,100); imagecopymerge($image,$split_sec,100,0,100,0,0,100,100); imagecopymerge($image,$split_thir,200,0,200,0,0,100,100); imagecopymerge($image,$split_thir,300,0,300,0,0,100,100); imagepng($image); imagedestroy($image); header('Content-Type: image/png'); echo $image; ?> Hello, Just to keep things looking fresh I have a series of over a hundred images that displays randomly, five across, toward the header of my site. See here... Jump around the site or refresh the page now and then...you will see the images will randomly fail to show through. http://www.clipartillustration.com/ Without a doubt they are also loading slower than they should too. As far as I can tell, everything should be fine! See below code. I think the only thing messing it up is the random image function itself is quirky. $imagecount = 0; while($imagecount < 5){ $start = "1"; $random = rand($start, $total); $image_name = $random . $file_type; echo "<img class=\"scrollingimage\" alt=\"\" height=\"105\" width=\"124\" src=\"$image_folder/$image_name\" />"; $imagecount ++; } Hey,
This is my first day with PHP and I'm given an assignment by my professor. Assignment is a very basic game, all i have to do is give 2 random numbers, and add them, and check if the user has submitted the correct answer.
So i thought like this;
1- first php file generates two random numbers
1.1- user submits the sum of those numbers
2- second php file, gets the sum of the random generated numbers and checks if the submitted value is right.
I've come up this far;
<?php echo "<html><head><title>calculation game!</title></head><body>"; echo "<h1>first number is</h1>"; echo (rand(100, 450)); echo "<h1>and the next number is</h1>"; echo (rand(100, 5000)); echo "<h1>now add the numbers and submit your output here!</h1>"; echo "<form name = \"myfirstform\" action = \"formprocess.php\" method = \"PO$ echo "Enter data<br>"; echo "<input type = \"text\" name = \"firstdata\">"; echo "<br> <input type= \"submit\" value = \"Let's check!\">"; echo "</form>"; ?> Now my problem is about; how can I keep those generated numbers and add them up. I've been digging all through the internet for syntax and php scripts, but I couldn't find an answer that helps me. Thanks in advance. I've managed to isolate a problem I'm having with my php script. It would seem the script randomly restarts itself with blank post data while it's running. I've managed to mimick the problem using a very basic php script which just pauses and writes to a log: <?php $q = $_POST['q']; if ($q==""){ writelog ("MISFIRE!!!"); die; } writelog("\n*** Error check started ***"); for ($i = 1; $i <= 50; $i++) { writelog ($i); sleep(rand(2,20)); } function writelog($towrite) { $tdate=date('d/m/Y H:i:s'); $file = 'log/testlog.txt'; $current = $towrite." --- ".$tdate."\n"; file_put_contents($file, $current, FILE_APPEND); } writelog("*** Error check ended ***"); ?>To rule out any problems with my AJAX htmlhttp requests, I simply send the script some irrelevant post data using Chrome's Advanced Restful client. This is the ouput of the log from an example test run: *** Error check started *** --- 05/06/2014 18:27:30 1 --- 05/06/2014 18:27:30 2 --- 05/06/2014 18:27:44 3 --- 05/06/2014 18:27:49 4 --- 05/06/2014 18:27:59 5 --- 05/06/2014 18:28:04 6 --- 05/06/2014 18:28:22 7 --- 05/06/2014 18:28:33 8 --- 05/06/2014 18:28:39 9 --- 05/06/2014 18:28:52 10 --- 05/06/2014 18:29:08 11 --- 05/06/2014 18:29:22 12 --- 05/06/2014 18:29:30 13 --- 05/06/2014 18:29:43 MISFIRE!!! --- 05/06/2014 18:29:46 14 --- 05/06/2014 18:29:56 15 --- 05/06/2014 18:30:07 16 --- 05/06/2014 18:30:09 17 --- 05/06/2014 18:30:15 18 --- 05/06/2014 18:30:32 19 --- 05/06/2014 18:30:52 20 --- 05/06/2014 18:30:54Note the logged "Misfire" after the 13th entry. This shows the script tried to run again with blank post data, the same problem I'm having in my more complex script. Why could this be happening? It's not anyone else calling the script, nobody knows about the site and I've ruled it out by logging the IP in my real script. Edited by holdorfold, 05 June 2014 - 02:29 PM. |