PHP - A Simple Way To Randomly Choose Between From Two Strings
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 ? Similar TutorialsHi 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 Basically what I am trying to do is create an upload form so that I may choose what predetermined directory in a drop down to upload the file to. For example if I want to upload 'image.jpg' to the folder 'family' I can then use a drop down, select family and upload the image. So far I have yet to find a script similar to what I am trying to do. I see regular upload scripts, but nothing so that I can choose a predetermined directory. Any ideas? I need to choose a random number that doesn't currently exist in the database Dear everyone, I am reasonably new to php, so there is a chance that what I am asking for may exceed my grasp. Nevertheless I'd like to try: Is it possible to let the user choose (by using a drop down listbox for instance) which table from a database to display on a page? And/or which database to display on a page? Background information: I'm working on a website for my chess club. I've already got a working page (html,css) with a table of the standings (mysql, php) of the latest round (with position number, name, points, wins, losses, etc). By clicking on the column header, it sorts the respective column. What I'd finally like to do is let the user choose to display a different round (table), or even a different season (database). I could make a seperate page for each round, but I'd like to know if there's a more elegant way to do this by using only one page and one or more databases. Thanks in advance for any tips and best wishes from The Netherlands, Wouter. I'm trying to work out if in my form my image field, which currently asks the user to upload from their hard drive, can show the contents of a server folder to select an image or upload a new one. Can this be done?? First of all, sorry if this is in the wrong section but I'm getting desperate at the moment and need some help.. I'm working with wordpress and will be creating a website which will cover news/reviews/etc on different subjects. (Gaming, android, iOS etc.) Now I want one page to be a general gaming page on which we'll post news about Nintendo, PlayStation, PC gaming etc. However, I want people to be able to choose one or more categories on this page. For example, if a user wouldn't want to read nintendo news it should filter those posts out.. If a user only wanted xbox news it should filter out everything but xbox posts. I asked this on the Wordpress forums as well and someone else beat me to it a couple years ago, but the topic has been closed and due to the lack of a PM-ing system on their forums it's impossible to see what fixed the issue.. http://wordpress.org/support/topic/let-user-toggle-post-visibility-by-category-oder-tag?replies=4 Hoping that someone out there can help, thanks in advance I know the title is a bit confusing but I wasn't exactly sure how to describe my issue and none of my numerous searches online and here returned any positive results for a solution. What I'm trying to do is allow a user to 'choose' one set from multiple sets of numbers for inclusion into the database. The image below should with the visualization of my goal. As you can see from the above image, there's a "button" to the right that states "keep this set". My goal is to allow the user to click the button and the corresponding set of values is then entered into the database as a string (the values aren't being used in any calculations afterwards just being displayed on screen.) The following code below works for auto-insertion if there's only one set generated but nothing I've attempted so far works when it comes to allowing the user to choose one set they'd like entered. <?php additional code here... echo '<table><tr><td>'; for($i=1; $i<=$Sets; $i++){ $Stat_Results = GenStats($uId, $StartSet, $SetOption); echo "Stat values for ".$SetGenerated[$i]; foreach($Stat_Results as $key => $DisplayStats){ echo $DisplayStats.', '; } if($Sets == 1){ $SetResults = implode(',',$Stat_Results); DB_Insert($uId, $SetResults, $TimeStamp); }else if($Sets >= 2){ echo "</td><td> => <input type='button' name='submit' value='keep this set'></td> <tr><td>"; } } echo '</td></tr></table>'; ?> html below here....Variables: $sId, $StartSet, $SetOption, $Sets, $uId, and $TimeStamp are all set in a section not shown in this snippet. I've tried Javascript but too be honest, I'm not all that familiar with it (though I am trying to become more fluid in it) and I've went so far as to try to create the multiple sets as a dropdown box thinking the user could simply select it from there and it be treated as a dynamic form and php would do the rest. But that didn't work either. The form button for submission is the remnant of the <select> list I tried to generate. The form is no longer there. I left the button in to generate the image you see above and has since been removed from the actual code. I admit, I'm stuck and need some guidance because I can't seem to make this work no matter what I do. I realize $Stat_Results is a multidimensional array and contains all the values of each set in their respective array, but so far, I'm at a stand still on properly retrieving those values for insertion. Thanks to all who read and attempt to help! Edited by Cryotech, 01 December 2014 - 03:08 PM. I have some code where i input data and upload images to a database (working 100% correctly) However I want to expand on it - what I want is when a user uploads an image of their choice, to assign it to a directory of their choosing. Then, when input is successful, write the directory of where the image is stored (not just the image) to the database. Here is the code; Code: [Select] <?php ini_set('display_errors',1); error_reporting(-1); require_once ('./includes/config.inc.php'); require_once (MYSQL); $add_cat_errors = array(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Check for a name: if (empty($_POST['product'])) { $add_cat_errors['product'] = 'Please enter the name!'; } // Check for a description: if (empty($_POST['prod_descr'])) { $add_cat_errors['prod_descr'] = 'Please enter the description!'; } // Check for a category: if (!isset($_POST['cat']) || !filter_var($_POST['cat'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_product_errors['cat'] = 'Please select a category!'; } // Check for a price: if (empty($_POST['price']) || !filter_var($_POST['price'], FILTER_VALIDATE_FLOAT) || ($_POST['price'] <= 0)) { $add_cat_errors['price'] = 'Please enter a valid price!'; } // Check for an image: if (is_uploaded_file ($_FILES['image']['tmp_name']) && ($_FILES['image']['error'] == UPLOAD_ERR_OK)) { $file = $_FILES['image']; $size = ROUND($file['size']/1024); // Validate the file size: if ($size > 512) { $add_cat_errors['image'] = 'The uploaded file was too large.'; } // Validate the file type: $allowed_mime = array ('image/jpeg', 'image/JPG', 'image/jpg'); $allowed_extensions = array ('.jpg', 'jpeg'); $image_info = getimagesize($file['tmp_name']); $ext = substr($file['name'], -4); if ( (!in_array($file['type'], $allowed_mime)) || (!in_array($image_info['mime'], $allowed_mime) ) || (!in_array($ext, $allowed_extensions) ) ) { $add_cat_errors['image'] = 'The uploaded file was not of the proper type.'; } // Move the file over, if no problems: if (!array_key_exists('image', $add_cat_errors)) { // Create a new name for the file: $new_name = (string) sha1($file['name'] . uniqid('',true)); // Add the extension: $new_name .= ((substr($ext, 0, 1) != '.') ? ".{$ext}" : $ext); // Move the file to its proper folder but add _tmp, just in case: $dest = "../db/images/$new_name"; if (move_uploaded_file($file['tmp_name'], $dest)) { // Store the data in the session for later use: $_SESSION['image']['new_name'] = $new_name; $_SESSION['image']['file_name'] = $file['name']; // Print a message: echo '<h4>The file has been uploaded!</h4>'; } else { trigger_error('The file could not be moved.'); unlink ($file['tmp_name']); } } // End of array_key_exists() IF. } elseif (!isset($_SESSION['image'])) { // No current or previous uploaded file. switch ($_FILES['image']['error']) { case 1: case 2: $add_cat_errors['image'] = 'The uploaded file was too large.'; break; case 3: $add_cat_errors['image'] = 'The file was only partially uploaded.'; break; case 6: case 7: case 8: $add_cat_errors['image'] = 'The file could not be uploaded due to a system error.'; break; case 4: default: $add_cat_errors['image'] = 'No file was uploaded.'; break; } // End of SWITCH. } // End of $_FILES IF-ELSEIF-ELSE. // Check for a stock: if (empty($_POST['stock']) || !filter_var($_POST['stock'], FILTER_VALIDATE_INT, array('min_range' => 1))) { $add_cat_errors['stock'] = 'Please enter the quantity in stock!'; } if (empty($add_cat_errors)) { $query = "INSERT INTO product (product, prod_descr, catID, price, image, stock) VALUES (?, ?, ?, ?, ?, ?)"; // Prepare the statement: $stmt = mysqli_prepare($dbc, $query); // For debugging purposes: // if (!$stmt) echo mysqli_stmt_error($stmt); // Bind the variables: mysqli_stmt_bind_param($stmt, 'sssssi', $name, $desc, $_POST['cat'], $_POST['price'], $_SESSION['image']['new_name'], $_POST['stock']); // Make the extra variable associations: $name = strip_tags($_POST['product']); $desc = strip_tags($_POST['prod_descr']); // Execute the query: mysqli_stmt_execute($stmt); if (mysqli_stmt_affected_rows($stmt) == 1) { // If it ran OK. // Print a message: echo '<h4>The product has been added!</h4>'; // Clear $_POST: $_POST = array(); // Clear $_FILES: $_FILES = array(); // Clear $file and $_SESSION['image']: unset($file, $_SESSION['image']); } else { // If it did not run OK. trigger_error('The product could not be added due to a system error. We apologize for any inconvenience.'); unlink ($dest); } } // End of $errors IF. } else { // Clear out the session on a GET request: unset($_SESSION['image']); } // End of the submission IF. require_once ('./includes/form_functions.inc.php'); ?> <form enctype="multipart/form-data" action="add_product.php" method="post" accept-charset="utf-8"> <input type="hidden" name="MAX_FILE_SIZE" value="524288" /> Product<br /><?php create_form_input('product', 'text', $add_cat_errors); ?> Description<br /><?php create_form_input('prod_descr', 'textarea', $add_cat_errors); ?> Category<br /><select name="cat"<?php if (array_key_exists('cat', $add_cat_errors)); ?>> <option>Select One</option> <?php // Retrieve all the categories and add to the pull-down menu: $q = 'SELECT catID, cat FROM category ORDER BY cat ASC'; $r = mysqli_query ($dbc, $q); while ($row = mysqli_fetch_array ($r, MYSQLI_NUM)) { echo "<option value=\"$row[0]\""; // Check for stickyness: if (isset($_POST['cat']) && ($_POST['cat'] == $row[0]) ) echo ' selected="selected"'; echo ">$row[1]</option>\n"; } ?> </select><?php if (array_key_exists('cat', $add_cat_errors)) echo $add_product_errors['cat']; ?> Price<br /><?php create_form_input('price', 'text', $add_cat_errors); ?> Image<br /><?php // Check for an error: if (array_key_exists('image', $add_cat_errors)) { echo $add_cat_errors['image'] . '<br /><input type="file" name="image"/>'; } else { // No error. echo '<input type="file" name="image" />'; // If the file exists (from a previous form submission but there were other errors), // store the file info in a session and note its existence: if (isset($_SESSION['image'])) { echo "<br />Currently '{$_SESSION['image']['file_name']}'"; } } // end of errors IF-ELSE. ?> <br /> <select name="select"> <option value="full_heads">db/images/full_heads</option> <option value="human_hair">db/images/human_hair</option> </select> Stock<br /><?php create_form_input('stock', 'text', $add_cat_errors); ?> <input type="submit" value="Add This Product" class="button" /> </fieldset> </form> How do I achieve this? 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? 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. 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? 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.. 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. 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 Hello Everyone, I am a noob at PHP so please forgive me if my code is wrong. I have a strong understanding of HTML and CSS just for the curious. Question: Write a program that formats a block of text (to be input by the user) based on preferences chosen by the user. Give your user options for color of text, font choice and size. Display output on a new page. I would greatly appreciate someone's help. The text is showing up but not according to the options selected. I know there is something wrong with the output page. Here is the Input Page (call it question4.php): <html> <head> <title> Please Enter Your Text</title> </head> <body> <form method="post" action="question4display.php"> <p>Enter the text you want formatted please: <input type="text" name="textformat" maxlength="30" size="30" /> <table> <tr> <td><label for="font">Select Font:</label></td> <td><select id="font" name="font"> <option value="Verdana">Verdana</option> <option value="Arial">Arial</option> <option value="Times New Roman">Times New Roman</option> </select> </td> </tr> <tr> <td><label for ="size">Select Size:</label></td> <td><select id="size" name="size"> <option value="10px">10px</option> <option value="12px">12px</option> <option value="14px">14px</option> <option value="20px">20px</option> </select> </td> </tr> <tr> <td><label for="color">Select Color:</label></td> <td><select id="color" name="color"> <option value="green">Green</option> <option value="blue">Blue</option> <option value="red">Red</option> </select> </td> </tr> </table> <input type="submit" name="submit" value="Submit" /> </form> </body> </html> Here is the OUTPUT page (called it:question4display.php): <?php session_start(); $_SESSION['textformat'] = $_POST['textformat']; $_SESSION['font'] = $_POST['font']; $_SESSION['size'] = $_POST['size']; $_SESSION['color'] = $_POST['color']; ?> <html> <head> </head> <body> <p <?php echo ' style="font-family: ' . $_POST['font'] . '; '; echo 'font-size: ' . $_POST['size'] . '; '; echo 'color: ' . $_POST['color'] . '; '; ?> > <?php echo $_POST['textformat']; ?> </p> </body> </html> 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! 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. 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';
|