PHP - How Can I Generate A Random Variable?
Hi, im trying to apply a random css class to a div so that a random image is generated on each refresh. This is the code i am using to apply the class.
Code: [Select] <div class="<?php echo($randomimage); ?>"> Say i have an array of $image1 $image2 $image3 etc, how can i make $randomimage = 1 of these at random on each refresh? I've found lots of tutorials that generate a random number online but none that generate a random variable and am having trouble piecing this together. Any help would be hugely appreciated. Richard Similar TutorialsHi there. I need a function that can generate 15 random numbers between (1,10) and then converts those numbers to Roman numbers. Anyone can help me? So I found this code from someone else on here who posted about creating a random string. I've copied the code for myself but when I upload php page to my server and view source... there is no php code. Essentially, i see no randomly generated text. what am i missing? Code: [Select] <?php function genRandomString() { $length = 5; $characters = array_merge(range(0,9),range('a','z'),range('A','Z')); $string = ""; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, count($characters)-1)]; } return $string; } ?> Hi, I have a script to add images to my tabel and and upload them to my server, I have managed to get the upload script to rename the image with a 5 digit random number on the end to prevent overwriting, the only problem I can't seem to be able to add the same name to my tabel. Any ideas? Thanks in advance. Code: [Select] <?php $idir = "uploads/"; // Path To Images Directory if (isset ($_FILES['fupload'])){ //upload the image to tmp directory $url = $_FILES['fupload']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload']['type'] == "image/jpg" || $_FILES['fupload']['type'] == "image/jpeg" || $_FILES['fupload']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload']['tmp_name'], $idir. basename($_FILES['fupload']['name'], $file_ext).rand(10000 , 99999).$file_ext); // Move Image From Temporary Location To Perm } } if (isset ($_FILES['fupload2'])){ //upload the image to tmp directory $url = $_FILES['fupload2']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload2']['type'] == "image/jpg" || $_FILES['fupload2']['type'] == "image/jpeg" || $_FILES['fupload2']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload2']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload2']['tmp_name'], "$idir" . $_FILES['fupload2']['name'] $file_ext).rand(10000 , 99999).$file_ext); // Move Image From Temporary Location To Permanent Location } } if (isset ($_FILES['fupload3'])){ //upload the image to tmp directory $url = $_FILES['fupload3']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload3']['type'] == "image/jpg" || $_FILES['fupload3']['type'] == "image/jpeg" || $_FILES['fupload3']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload3']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload3']['tmp_name'], "$idir" . $_FILES['fupload3']['name'] $file_ext).rand(10000 , 99999).$file_ext); // Move Image From Temporary Location To Permanent Location } } if (isset ($_FILES['fupload4'])){ //upload the image to tmp directory $url = $_FILES['fupload4']['name']; // Set $url To Equal The Filename For Later Use if ($_FILES['fupload4']['type'] == "image/jpg" || $_FILES['fupload4']['type'] == "image/jpeg" || $_FILES['fupload4']['type'] == "image/pjpeg") { $file_ext = strrchr($_FILES['fupload4']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php $copy = copy($_FILES['fupload4']['tmp_name'], "$idir" . $_FILES['fupload4']['name'] $file_ext).rand(10000 , 99999).$file_ext); // Move Image From Temporary Location To Permanent Location } } $usr = "user"; $pwd = "pass"; $db = "db"; $host = "host"; # connect to database $cid = mysql_connect($host,$usr,$pwd); if (!$cid) { echo("ERROR: " . mysql_error() . "\n"); } if ($_POST['submit']) { $logo = mysql_real_escape_string("$idir" . $_FILES['fupload']['name']); $image1 = mysql_real_escape_string("$idir" . $_FILES['fupload2']['name']); $image2 = mysql_real_escape_string("$idir" . $_FILES['fupload3']['name']); $image3 = mysql_real_escape_string("$idir" . $_FILES['fupload4']['name']); $SQL = " INSERT INTO mhhire "; $SQL .= " image1, image2, image3, logo) VALUES "; $SQL .= " ('$image1', '$image2', '$image3', '$logo') "; $result = mysql_db_query($db,$SQL,$cid); $last=mysql_insert_id(); if (!$result) { echo("ERROR: " . mysql_error() . "\n$SQL\n"); } header("location:thanks.php"); exit(); } ?> How do you generate a random number like say, 0 through 10? I want to select random sites from my database that have IDs 0 through 10. Hi All, I created this simple function to generate random doubles..... Please your opinions! function GetRandomFloatNumber($min = false, $max = false, $dec_min = false, $dec_max = false) { // Seed the generator mt_srand((double)microtime()*1000000); // Set the default min and max if no parameter has been passed if ($min === false) $min = 0; if ($max === false) $max = mt_getrandmax(); if ($dec_min === false) $dec_min = 0; if ($dec_max === false) $dec_max = mt_getrandmax(); // units $units = mt_rand($min, $max); // Decimals $decimals = mt_rand($dec_min, $dec_max); // Set double $doublenumber = $units.'.'.$decimals; // Return double return $doublenumber; } How to generate a unique random number in php??? Any one who can help me? hi!, is it possible to use rand() to generate unique number that will be saved in a database as a primary key? Since i dont want to have numbers like 00001 incrementing on the table. They dont look like real account numbers... i need something like 45642 or 95452 and the like. thanks in advance. I am looking to generate a random number for every user contribution as a title of the contribution. I could simply check the database each time with a query and generate a number which does not equal to any of the entries of the database. But I imagine this as inefficient and it could become slow if the database is big in my opinion. Also I'd have to contain all the numbers of the database somewhere to manage the "not equals to", in an array or something similar but that can end up as a giant one. Excuse the layman's speech I am new to this. Any suggestions how this can be solved efficiently without straining the resources too much? You can explain it linguistically and do not have to provide me any scripts, I will figure it out. Hello........ Currently i am struggling with php script....... can any one tell me or guide me how to code Automatically generating random number with in the range of 19 to 90 and the number has to change with in 24 hours time duration......... It's urgent........ Thanks in advance..... Rooban.S This might be a bit hard to explain! I have a grid, 32x32 which is actually 1024 mySQL rows in a table, you can see the table he http://interbitlotto.com/grid each cell is a row in the database, top left is ID 1, bottom right is id 1024. get it? right well its a battle ship game, and im stuck on the automatic battle ship placement script. I have displayed the generated boats as misses so we can see them. The problem i am having, is that the random number generater chooses a cell too close to the side so the boat ends up wrapping to the other side. I cant think of a way to detect if its going to wrap, if it is then choose another cell... The code below chooses the orientation of the boat, then chooses a random cell... but as you can see, no code for "across" to stop it choosing one too close to the side. Any ideas? Code: [Select] $orientation = rand(1,2); //get random orientation - 1 = down, 2 = across. if ($orientation == 1){ $multiply = 32; //cells till next row $max = 1024 - (32 * $boatlength); //prevents it from choosing a cell too close to the bottom $startcell = rand(1,$max); }else{ $multiply = 1; //across, so next cell $max = 1024; $startcell = rand(1,$max); } Hi, What I'm trying to do is create a script that generates a random list of cars whenever it is run. I have a list of available cars in a MySQL database. I'm just not sure how to get php to generate a list of, say, 20 cars, that are randomly picked from the cars in the database. I may also want to add other statistics like MPG (also already in the database). Can anyone show me how to do this? And is it possible to format the returned data in a table or div format? Thanks in advance Unk Basically I am setting up my own cricket management game, but there are 3 areas that I am slightly stuck on and would appreciate help: 1) When a use registers, I need to create 11 players for their team. For this, I am going to have one text files with first names and one text file with surnames. How can I open each file and select a name and then match them together? 2) I need to create the list of games to be executed at particular times through a cron job. How can I go through all the teams in a table and match them together in games, ensuring everyone plays everyone? If a new player registers, he will be put into a random league and so the games for that league will have to be redone 3) How can I set up a cron job to execute the above games? Each team should play once a day and so if there are 24 teams in a table, there will be 12 games that occur through this cron job. I assume cron jobs are the best thing for this. Any help would be appreciated. Thanks. I have a recursive sql query. I'm doing this with an sql query as a function. Here is the function: function select() { $sql="SELECT cat FROM $scat"; if($result=$mysqli->query($sql)){ if($result->num_rows>0){ $level =+1; echo<<<HTML <div class="menutitles"> onmouseover="document.getElementById('$scat').style.display='block';document.getElementById('$scat2').style.display='block';" onmouseout="document.getElementById('$scat').style.display='none';document.getElementById('$scat2').style.display='block';" > <a class="topseltxt2" href="gem.php?cat=$scat"></a><br/> <div class="contain" id="$scat"> <div class="menuitems" id="$scat2"> HTML; select(); }else{$level=-1; if($level==1){echo" <a class='topseltxt' href='gem.php?cat=$scat'></a><br/> "; }else{ While($row=$result->fetch_array()){ $scat=replace($row[cat]); echo" <a class='topseltxt2' href='gem.php?cat=$scat'></a><br/> ";} } } } } and this is the database query with the function added to it: $level=1; $count=0; $sql = "SELECT cat FROM dczcat1 ORDER BY position"; if ($result = $mysqli->query($sql)){ if ($result->num_rows > 0){ $count=+1; while ($row = $result->fetch_array()){ $scat=replace($row[cat]); $scat2=replace($row[cat]) . 2; $cat=$row[cat]; $sql="SELECT cat FROM $scat"; if($result=$mysqli->query($sql)){ $count=+1; if($result->num_rows>0){ $level =+1; echo<<<HTML <div class="menutitles"> onmouseover="document.getElementById('$scat').style.display='block';document.getElementById('$scat2').style.display='block';" onmouseout="document.getElementById('$scat').style.display='none';document.getElementById('$scat2').style.display='block';" > <a class="topseltxt2" href="gem.php?cat=$scat"></a><br/> <div class="contain" id="$scat"> <div class="menuitems" id="$scat2"> HTML; select(); }else{$level=-1; if($level==1){echo" <a class='topseltxt' href='gem.php?cat=$scat'></a><br/> "; }else{ While($row=$result . $count->fetch_array()){ $scat=replace($row[cat]); echo" <a class='topseltxt2' href='gem.php?cat=$scat'></a><br/> ";} } } }echo"</div> </div> </div>"; } } } I get the error: Fatal error: Call to a member function fetch_array() on a non-object in /home/kangerc1/public_html/zleftsidebar.php on line 60 I think this is because I am using $result more than once and I need to call it $result1 $result2 $result3 etc. but how can I generate the name of the variable? Hello, Do you guys have any idea how to start an Automatic Order Number System in PHP? I have an service Website, where you can purchase something, and i want after the redirect to "Success.php" to generate an order number, to be shown to the buyer and saved in Date Base for me. Any solutions helps. I´m beginner so don´t mind
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. Can this be done with php? aaa aab aac ... zzz <?php if(isset($_POST['submit'])){ //collect form data $location = $_POST['location']; $ID = $_POST['ID']; $section = $_POST['section']; //check name is set if($location ==''){ $error[] = 'Name is required'; } //if no errors carry on if(!isset($error)){ # Title of the CSV $Content = "location, ID, section\n"; //set the data of the CSV $Content .= "$location, $ID, $section\n"; # set the file name and create CSV file $my_file = ("$location$ID$section.cvs"); $handle = fopen("$my_file", "w") or die('Cannot open file: '.$my_file); header('Content-Type: application/csv'); header('Content-Disposition: attachment; filename="' . $FileName . '"'); echo $Content; exit(); } } //if their are errors display them if(isset($error)){ foreach($error as $error){ echo "<p style='color:#ff0000'>$error</p>"; } } ?> <form action='' method='post'> <p><label>Location:</label><br><input type='text' name='location' value=''></p> <p><label>ID:</label><br><input type='text' name='ID' value=''></p> <p><label>Section:</label><br><input type='text' name='section' value=''></p> <p><input type='submit' name='submit' value='Submit'></p> </form>I have wrote a .php file which is a form with 3 different fields, in these fields I want to write entries which lateron will be submitted into a .csv generating a csv file on my server with the name of the entries. The issue is that the file is not being generated on my server. With the current code the entries are being recognized and being placed in the filename of the csv. The point is not to make it downloadable sinds I want to have it on my webserver and keep editing information in it. My code is top of this post. My .php file replies that: Cannot open file: BOD10Buffer.csv Pardon my sloppy code everyone, I am not really a person that codes but this "form" may save me a lot of time in the longrun, just difficult and I am asking for help on this. Is there anyone that may be kind enough to help me? and as to what I might be doing wrong? All help is much appreciated! Hi, can someone help me to understand this? What i want to do is to write some information in a form and after i submit the form that data will be in a new php page. Thanks in advance Hi guys, so i have this file upload script. When i upload a file it gets stored in /uploads and keeps the same file name. So if i upload a file "test.exe" the file will be available at uploads/test.exe
What i want is that it generates a new file name like: "9daln292os.exe" so upload/9daln292os.exe
This is my code:
<?php // Where the file is going to be placed $target_path = "uploads/"; /* Add the original filename to our target path. Result is "uploads/filename.extension" */ $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); $_FILES['uploadedfile']['tmp_name']; ?> <?php $file_type = $_FILES['userfile']['type']; $file_name = $_FILES['userfile']['name']; $file_ext = strtolower(substr($file_name,strrpos($file_name,"."))); if (!in_array($file_type, $FILE_MIMES) && !in_array($file_ext, $FILE_EXTS) ) $message = "Sorry, $file_name($file_type) is not allowed to be uploaded."; else $message = do_upload_function_here($upload_path_here, $upload_ur_upload_url_herel); ?> <?php $target_path = "uploads/"; $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded. Here is the link to your file: <a href=uploads/". basename( $_FILES['uploadedfile']['name']). ">". basename( $_FILES['uploadedfile']['name'])."</a>"; } else{ echo "There was an error uploading the file, please try again!"; } ?>I don't know any basic php i really need someone to give me the code ready please. Thanks much appreciated. Edited by darox, 21 July 2014 - 01:07 PM. |