PHP - Generate Random Items/numbers From Data In A Database
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 Similar TutorialsHow 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 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? 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 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. Hi all, This is something related with php as well as java script. If anyone can help me regarding this issue i would be very pleased. In a particular form, i have 2 fields namely customer id and Account type. Since there are many account types it is stored as a jump menu. There are seperate tables in my database to represent each of those accounts types. There is a seperate field in each table called account number which is auto incremented. If i select a particular account type in my form, i want to get the account number which is relevant to that account type. For an example if i click the submit button a message should appear like " A new ..........( relevant account type) has been successfully opened" Any idea of how this could be done? Thanks, Heshan. hi. i am making mcq type test. lot of questions stored in db, i want that some of them retrieve i.e. 5 after 5 test should end. how is hould do, query is ...SELECT question,questionid, choice1, choice2, choice3, choice4, answer FROM questionbank order by RAND() limit 1";... limit 1 is used for display one question in a page. I have a webpage where all the database items are displyes in a table format.The table also has a check box.Upon clicking the delete button i need to delete all the items whish has the checkbox checked. How will i do that I have this array of items in my php file.
$items = array( array("id" => 100,"categorypath" => "level1/powders", "product" => "Mens powder"), array("id" => 200,"categorypath" => "level1/oils/sunflower", "product" => "XYZ oil"), array("id" => 300,"categorypath" => "level1/eatable/vegetables", "product" => "carrot"), array("id" => 400,"categorypath" => "level1/oils/sunflower", "product" => "ABC oil"), array("id" => 500,"categorypath" => "level1/eatable/fruits", "product" => "mango"), array("id" => 600,"categorypath" => "level1/eatable/vegetables", "product" => "spinach"), array("id" => 700,"categorypath" => "level2/baby items/toys", "product" => "puzzle block"), array("id" => 800,"categorypath" => "level2/baby items/toys", "product" => "trucks and cars"), array("id" => 900,"categorypath" => "level2/baby items/clothes", "product" => "shirts"), array("id" => 1000,"categorypath" => "level1/powders", "product" => "Womens powder"), array("id" => 1100,"categorypath" => "level1/oils/groundnut", "product" => "GN oil"), ); Using the above array I am trying to generate a JSON file that will have the following structu
{ "category":[ { "categoryName":"level1", "category":[ { "categoryName":"powders", "products":[ { "id":"100", "path":"level1/powders", "prodname":"Mens powder" }, { "id":"1000", "path":"level1/powders", "prodname":"Womens powder" } ] }, { "categoryName":"oils", "category":[ { "categoryName":"sunflower", "products":[ { "id":"200", "path":"level1/oils/sunflower", "prodname":"XYZ oil" }, { "id":"400", "path":"level1/oils/sunflower", "prodname":"ABC oil" } ] }, { "categoryName":"groundnut", "products":[ { "id":"1100", "path":"level1/oils/groundnut", "prodname":"GN oil" } ] } ] }, { "categoryName":"eatable", "category":[ { "categoryName":"vegetables", "products":[ { "id":"300", "path":"level1/eatable/vegetables", "prodname":"carrot" }, { "id":"600", "path":"level1/eatable/vegetables", "prodname":"spinach" } ] }, { "categoryName":"fruits", "products":[ { "id":"500", "path":"level1/eatable/fruits", "prodname":"mango" } ] } ] } }, { "categoryName":"level2", "category":[ { "categoryName":"baby items", "category":[ { "categoryName":"toys", "products":[ { "id":"700", "path":"level2/baby items/toys", "prodname":"puzzle blocks" }, { "id":"800", "path":"level2/baby items/toys", "prodname":"trucks and cars" } ] }, { "categoryName":"clothes", "products":[ { "id":"900", "path":"level2/baby items/clothes", "prodname":"shirts" } ] } ] } ] } Not being an expert in php, I have somehow managed to reach thus far in my code, but can not quite arrive at the correct logic. Having trouble with handling associative arrays and objects in php. (Javascripting is much easier I feel) So far I have managed to fix all the errors/warning in my code. Here is my full php code:
$items = array( array("id" => 100,"categorypath" => "level1/powders", "product" => "Mens powder"), array("id" => 200,"categorypath" => "level1/oils/sunflower", "product" => "XYZ oil"), array("id" => 300,"categorypath" => "level1/eatable/vegetables", "product" => "carrot"), array("id" => 400,"categorypath" => "level1/oils/sunflower", "product" => "ABC oil"), array("id" => 500,"categorypath" => "level1/eatable/fruits", "product" => "mango"), array("id" => 600,"categorypath" => "level1/eatable/vegetables", "product" => "spinach"), array("id" => 700,"categorypath" => "level2/baby items/toys", "product" => "puzzle block"), array("id" => 800,"categorypath" => "level2/baby items/toys", "product" => "trucks and cars"), array("id" => 900,"categorypath" => "level2/baby items/clothes", "product" => "shirts"), array("id" => 1000,"categorypath" => "level1/powders", "product" => "Womens powder"), array("id" => 1100,"categorypath" => "level1/oils/groundnut", "product" => "GN oil"), ); $jsonStruct = array(); function jsonCreateStruct(){ GLOBAL $items; for($c=0; $c<count($items); $c++){ $categ = $items[$c]["categorypath"]; insertJson($categ, $items[$c]); } } function insertJson($catg, $itm){ GLOBAL $jsonStruct; $exp = explode("/",$catg); print_r("\n\n\n $catg \n"); if(count($exp) == 1){ print_r("Level 1 \n"); if(!isset($jsonStruct[0])){ $jsonStruct[0]["categoryName"] = $exp[0]; $jsonStruct[0]["products"] = array($itm); print_r("\nCreated:: $exp[0]"); }else{ $notFound = true; for($j=0; $j<count($jsonStruct); $j++){ $catgName = $jsonStruct[$j]["categoryName"]; print_r("\nFound: $catgName"); if($catgName == $exp[0]){ $notFound = false; if($jsonStruct[$j]["products"]){ array_push($jsonStruct[$j]["products"],array($itm)); }else{ $jsonStruct[$j]["products"] = array(); array_push($jsonStruct[$j]["products"],array($itm)); } } } if($notFound){ print_r("\nNotFound\n"); array_push($jsonStruct,array("categoryName"=> $exp[0], "products" => array($itm))); } } } if(count($exp) == 2){ print_r("Level 2 \n"); if(!isset($jsonStruct[0])){ $jsonStruct[0]["categoryName"] = $exp[0]; $jsonStruct[0]["categorypath"] = array("categoryName" => $exp[1], "products" => array($itm)); print_r("\nCreated:: $exp[0] / $exp[1]"); }else{ $notFound1 = true; $notFound2 = true; $indexLevel = null; for($j=0; $j<count($jsonStruct); $j++){ $catgName1 = $jsonStruct[$j]["categoryName"]; print_r("\nFound: $catgName1"); if($catgName1 == $exp[0]){ $notFound1 = false; $indexLevel = $j; if(isset($jsonStruct[$j]["categorypath"])){ $level1 = $jsonStruct[$j]["categorypath"]; for($m=0; $m<count($level1); $m++){ if(isset($level1[$m]["categoryName"])){ $catgName2 = $level1[$m]["categoryName"]; print_r("\nFound: $catgName2"); if($catgName2 == $exp[1]){ $notFound2 = false; if($level1[$m]["products"]){ array_push($jsonStruct[$j]["categorypath"][$m]["products"],array($itm)); }else{ $jsonStruct[$j]["categorypath"][$m]["products"] = array(); array_push($jsonStruct[$j]["categorypath"][$m]["products"],array($itm)); } } } } } } } if($notFound1){ print_r("\nNotFound1\n"); array_push($jsonStruct,array("categoryName"=> $exp[0], "categorypath" => array("categoryName" => $exp[1],"products" => array($itm)))); }else if($notFound2){ print_r("\nNotFound2\n"); // $jsonStruct[$indexLevel]["categorypath"] = array("categoryName"=> $exp[1], "products" => array($itm)); $jsonStruct[$indexLevel]["categorypath"] = array(); array_push($jsonStruct[$indexLevel]["categorypath"], array("categoryName"=> $exp[1], "products" => array($itm))); } } } if(count($exp) == 3){ print_r("Level 3 \n"); if(!isset($jsonStruct[0])){ $jsonStruct[0]["categoryName"] = $exp[0]; $jsonStruct[0]["categorypath"] = array("categoryName" => $exp[1], "categorypath" => array("categoryName" => $exp[2], "products" => array($itm))); print_r("\nCreated:: $exp[0] / $exp[1] / $exp[2]"); }else{ $notFound1 = true; $notFound2 = true; $notFound3 = true; $indexLevel1 = null; $indexLevel2 = null; for($j=0; $j<count($jsonStruct); $j++){ $catgName1 = $jsonStruct[$j]["categoryName"]; print_r("\nFound: $catgName1"); if($catgName1 == $exp[0]){ $notFound1 = false; $indexLevel1 = $j; if(isset($jsonStruct[$j]["categorypath"])){ $level2 = $jsonStruct[$j]["categorypath"]; for($m=0; $m<count($level2); $m++){ if(isset($level2[$m]["categoryName"])){ $catgName2 = $level2[$m]["categoryName"]; print_r("\nFound: $catgName2"); if($catgName2 == $exp[1]){ $notFound2 = false; $indexLevel2 = $m; if(isset($level2[$m]["categorypath"])){ $level3 = $level2[$m]["categorypath"]; for($n=0; $n<count($level3); $n++){ //print_r($level3["categoryName"]); if(isset($level3["categoryName"])){ $catgName3 = $level3["categoryName"]; print_r("\ncatgName3: ". $catgName3); if($catgName3 == $exp[2]){ $notFound3 = false; if($level3["products"]){ print_r("\npushing into array\n"); array_push($jsonStruct[$j]["categorypath"][$m]["categorypath"]["products"],array($itm)); }else{ print_r("\ncreate new and pushing into array\n"); $jsonStruct[$j]["categorypath"][$m]["categorypath"][$n]["products"] = array(); array_push($jsonStruct[$j]["categorypath"][$m]["categorypath"]["products"],array($itm)); } } } } } } } } } } } if($notFound1){ print_r("\nNotFound1\n"); array_push($jsonStruct, array("categoryName"=> $exp[0], "categorypath" => array("categoryName" => $exp[1],"products" => array($itm)))); }else if($notFound2){ print_r("\nNotFound2\n"); if(!$jsonStruct[$indexLevel1]["categorypath"]){ $jsonStruct[$indexLevel1]["categorypath"] = array(); } array_push($jsonStruct[$indexLevel1]["categorypath"], array("categoryName"=> $exp[1], "categorypath" => array("categoryName" => $exp[2], "products" => array($itm)))); }else if($notFound3){ print_r("\nNotFound3\n"); //$jsonStruct[$indexLevel1]["categorypath"][$indexLevel2]["categorypath"] = array("categoryName"=> $exp[2], "products" => array($itm)); if(!$jsonStruct[$indexLevel1]["categorypath"][$indexLevel2]["categorypath"]){ $jsonStruct[$indexLevel1]["categorypath"][$indexLevel2]["categorypath"] = array(); } array_push($jsonStruct[$indexLevel1]["categorypath"][$indexLevel2]["categorypath"], array("categoryName"=> $exp[2], "products" => array($itm))); } } } } jsonCreateStruct(); print_r("----------------------------------------"); print_r($jsonStruct); // echo json_encode($jsonStruct);
I have now reached a point where I desperately need help from experts.
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 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(); } ?> 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 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? 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); } 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. 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. hi, I am trying to create 7 lines, out of 49 numbers, each line must have unique numbers not seen in any other line so that every number out of 49 has been used in one of those lines, I also need them to be in order, lowest to highest except for the last number which needs to be completely any random ( as long as its not elsewhere in the 7 lines and its one of 49) I have made an attempt, <?php function code(){ for ($i=1; $i<=7; $i++){ $one = mt_rand(1, 49); echo $one; echo ' '; }} function lines(){ for ($i=1; $i<=7; $i++){ code(); echo '<br/>'; }} lines(); ?> but I am seriously failing at producing every number from 1 to 49 throughout those 7 lines and of course failing at ordering them with the random at the end that is not in order.. sorry if this sounds confusing but I would appreciate any help, thanks Hello all, I am newbie to php programming, any suggestions or advance greatly appreciated. I can't figure out how to output two array random numbers in ascending order. <?php $l_numbers = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47); $mega = range(1, 27); for($i = 0; $i <= 4; $i++) { $random1 = array_rand($l_numbers); echo "$random1 \n" ; } for($e = 1; $e <= 1; $e++) { $random2 = array_rand($mega); echo "<p> Mega number is $random2 </p>"; } echo "Winning numbers are $random1 and mega $random2"; ?> example: Winning numbers are 3,5,10,17,39 and mega 5. Ello Everyone! Ok, well I'm making a script with a file uploading thingy, and well, I'm also using a random number to generate a number they must write on a paper and upload it. Issue: I'm experiencing a slight issue with the random numbers though. Once the user uploads their photo with the numbers, I'll send it to my MySQL database. When it gets to that point the random numbers changes, and the numbers will change. I can not find a way to keep it as is, without it changing until the numbers have been placed into the database. //Top part $array = array(); for($i = 0; $i<5; $i++){ $array[$i] = rand(0,20); } $randNum = implode($array); //HTML part <form method="post" action="" enctype="multipart/form-data"> <table> <tr> <td> Generated Number: </td> <td> <h2> <?php echo $randNum ?> </h2> </td> </tr> <tr> <td> Group Name: </td> <td> <input type="text" name="group" maxlength="15" /> </td> </tr> <tr> <td> Photo Taken: </td> <td> <input type="file" name="image"/> </td> </tr> <tr> <th colspan="2"> <input name="submit" type="submit" value="Register As An Artist"/> </th> </tr> </table> </form> //SQL Part if($copied){ $createArtist = mysql_query("INSERT INTO `artistregister` (user_id, groupname, photo, randomnum) VALUES ('".$_SESSION['id']."', '".$groupName."', '".$filePath."', '".$thisRandom."')"); $resetArtist = mysql_query("UPDATE `accounts` SET `isArtist` = '1' WHERE `user_id` = '{$_SESSION['id']}'"); if($createArtist){ if($resetArtist){ echo "Your account is now pending for Artist Access. This could take upto a week."; $_SESSION['isArtist'] = 1; } else{ echo "There was an error, and it had been recorded. Please try again later."; sendError(mysql_error(), $_SERVER['REQUEST_URI']); } } else{ echo "There was an error, and it had been recorded. Please try again later."; sendError(mysql_error(), $_SERVER['REQUEST_URI']); } } elseif(!$copied){ echo "There was an error, and it has been recorded. Please try again later."; sendError("Line 98", $_SERVER['REQUEST_URI']); } I've tried looking for different functions, and such, but I'm either not looking in the right place or I'm just making some stupid logical error. Thank you for looking. Hi I have this simple code $one = rand(1,9); $two = rand(1,9); $three = rand(1,9); but I need to change it so that they are all unique and the same number is not used more than once can anyone help? thanks |