PHP - Generating Random Number And Inserting Into Database - With No Duplicates
I need a way to generate a random number and insert into a database, and I need the database to not contain any duplicates of that number. I basically need to generate a RMA # (Return Merchandise Authorization Number), so the numbers absolutely CAN NOT be duplicate. I have no ideas how to go about this.
Should I generate a random number, search the database and see if there's a duplicate, and if there is re-run the script? Similar TutorialsPlease i'm working on a project and i need to write a code that generates a unique random serial number.How can i go about it? Hi, I have a trouble figuring out how to properly convert a list of product data from XML into CSV format. My source is a XML file containing a list of products with attributes like color, size, material etc. with the following structu Code: [Select] <?xml version="1.0" encoding="utf-8" ?> <store> <products> <product> <name>T-Shirt</name> <price>19.00</price> <attributes> <attribute> <name>Color</name> <options> <option> <name>White</name> <price>0.00</price> </option> <option> <name>Black</name> <price>0.00</price> </option> <option> <name>Blue</name> <price>0.00</price> </option> </options> </attribute> <attribute> <name>Size</name> <options> <option> <name>XS</name> <price>-5.00</price> </option> <option> <name>S</name> <price>-5.00</price> </option> <option> <name>M</name> <price>0.00</price> </option> <option> <name>L</name> <price>0.00</price> </option> <option> <name>XL</name> <price>5.00</price> </option> </options> </attribute> </attributes> </product> <product> <name>Sweatshirt</name> <price>49.00</price> <attributes> <attribute> <name>Color</name> <options> <option> <name>White</name> <price>0.00</price> </option> <option> <name>Black</name> <price>0.00</price> </option> </options> </attribute> <attribute> <name>Size</name> <options> <option> <name>XS</name> <price>-10.00</price> </option> <option> <name>M</name> <price>0.00</price> </option> <option> <name>XL</name> <price>10.00</price> </option> </options> </attribute> <attribute> <name>Material</name> <options> <option> <name>Cotton</name> <price>10.00</price> </option> <option> <name>Polyester</name> <price>0.00</price> </option> </options> </attribute> </attributes> </product> <product> <name>Earrings</name> <price>29.00</price> </product> </products> </store> Each product has a number of elements like name, price etc. but also a random number of attributes (like color, size, material etc.) that also have a random number of options. Each option can affect the price of the product, so ordering a XS sized t-shirt can be cheaper than ordering a XL sized t-shirt. I would like to end up with a CSV representing one attribute combination on each line. In my example that would result in 3 colors x 5 sizes = 15 lines for the T-Shirt , 2 colors x 3 sizes x 2 materials = 12 lines for the Sweatshirt and 1 line for the Earrings without any attributes: Code: [Select] name,price,color,size,material T-Shirt,14.00,White,XS, T-Shirt,14.00,Black,XS, T-Shirt,14.00,Blue,XS, T-Shirt,14.00,White,S, T-Shirt,14.00,Black,S, T-Shirt,14.00,Blue,S, T-Shirt,19.00,White,M, T-Shirt,19.00,Black,M, T-Shirt,19.00,Blue,M, T-Shirt,19.00,White,L, T-Shirt,19.00,Black,L, T-Shirt,19.00,Blue,L, T-Shirt,24.00,White,XL, T-Shirt,24.00,Black,XL, T-Shirt,24.00,Blue,XL, Sweatshirt,49.00,White,XS,Cotton Sweatshirt,49.00,Black,XS,Cotton Sweatshirt,59.00,White,M,Cotton Sweatshirt,69.00,Black,M,Cotton Sweatshirt,69.00,White,XL,Cotton Sweatshirt,69.00,Black,XL,Cotton Sweatshirt,39.00,White,XS,Polyester Sweatshirt,39.00,Black,XS,Polyester Sweatshirt,49.00,White,M,Polyester Sweatshirt,49.00,Black,M,Polyester Sweatshirt,59.00,White,XL,Polyester Sweatshirt,59.00,Black,XL,Polyester Earrings,29.00,,, I already managed to generate the CSV Output for simple products like the Earrings and products with just one attribute, but am struggling to come up with a way to generate all possible product attribute combinations for products with more than one attribute. My miserable attempts at this so far have produced following code: Code: [Select] <?php mb_internal_encoding("UTF-8"); header('Content-Type: text/html; charset=utf-8'); $source = "example.xml"; $handle = fopen($source, "r"); $fp = fopen('export.csv', 'w'); $xml = simplexml_load_file($source); // Generate list of attributes (for csv header etc.) $header_attributes = array(); foreach ($xml->products->product as $product) { if(isset($product->attributes)) { foreach($product->attributes->attribute as $attribute) { array_push($header_attributes, $attribute->name); } } } $header_attributes = array_unique($header_attributes); $csvheader = array( 'name','price' // these exist for all products, could also include weight, image, description, special price etc... ); $static_csvheadercount = count($csvheader); foreach($header_attributes as $attribute) { array_push($csvheader, $attribute); // add variable number of attribute fields to csv header } fputcsv($fp, $csvheader); foreach ($xml->products->product as $product) { // loop through each product if(isset($product->attributes)) $simple = 0; else $simple = 1; if($simple == 1) { // if product is a simple product with no attributes $output=array(); array_push($output,(string)$product->name); array_push($output,(string)$product->price); for($i = $static_csvheadercount + $attribute_position; $i < count($csvheader); $i++) { array_push($output, ''); } fputcsv($fp, $output); } else { // is a configurable product with attributes $json = json_encode($product->attributes); $attributes = json_decode($json, TRUE); $attributes_number = count($product->attributes->attribute); if($attributes_number > 1) { // if product has more than 1 attributes so we have to generate each attribute combination // // I'm trying to figure out what should happen here // } else { // if product has only one attribute $attributename = (string)$product->attributes->attribute->name; $attribute_position = array_search($attributename, $header_attributes); $options_number = count($product->attributes->options->option); $pos = 1; foreach($attributes['attribute']['options']['option'] as $option) { $output=array(); array_push($output,(string)$product->name); array_push($output,(string)$product->price); for($i = $static_csvheadercount - 1; $i < ($static_csvheadercount + $attribute_position); $i++) { array_push($output, ''); } $output[$static_csvheadercount + $attribute_position] = $option['name']; for($i = $static_csvheadercount + $attribute_position; $i < count($csvheader) - 1 ; $i++) { array_push($output, ''); } fputcsv($fp, $output); $pos++; } $output=array(); array_push($output,(string)$product->name); array_push($output,(string)$product->price); for($i = $static_csvheadercount; $i < count($csvheader); $i++) { array_push($output, ''); } fputcsv($fp, $output); } } } ?> I've been stuck at this problem for hours unable to figure out a solution. Can someone give a few tips or pointer how to achieve the output for products with multiple attributes? Hey guys, I m not yet an experienced coder. SO faced alot of problems. Here, I'm trying to generate a UNIQUE RANDOM NUMBER set between two numbers. Repetative occurance must be avoided by all means as I want every number so generated bears a unique value. In other words, every values that made entry into the field of my database should be differant from each others. <?php $conN=mysql_connect("localhost","root",""); if(!$conN) { die('error'.mysql_error()); } mysql_select_db("freebie_allusers",$conN); $UIN=mt_rand(1,5); $locateUIN="SELECT UIN FROM user_info WHERE UIN='".$UIN."'"; $fetchUIN=mysql_query($locateUIN); $resultUIN=mysql_num_rows($fetchUIN); if($resultUIN>0) { WHAT CODE IS REQUIRED HERE SO AS TO GENERATE UNIQUE RANDOM NUMBER? } else echo $UIN; ?> Thanx in advance 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. Hello, I am using the following code to display images managed by a MySQL database. Basically another program manages a bunch of images, but this script displays certain ones (ones with INCLUDE = 1 in the database) on my main page. My question is, is there an easy way to limit the number of images it displays, say to 5? I'm not too concerned which images actually display (ascending or descending)... or better yet, random! Most importantly, I only want five to display. Each image will be linked to the full page, which displays all the images. Any ideas? Thanks! Code: [Select] <?php $username="XXXXXXX"; $password="XXXXXXX"; $database="XXXXXXX"; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query="SELECT * FROM ft_form_12 WHERE col_24='1'"; // $query="SELECT * FROM ft_form_12"; // SELECT * FROM ft_form_12 WHERE col_24='1' $result=mysql_query($query); $num=mysql_numrows($result); mysql_close(); ?> <?php $i=0; while ($i < $num) { $f20=mysql_result($result,$i,"col_23"); //Photo file name $f21=mysql_result($result,$i,"col_24"); //INCLUDE ?> <a href="http://www.domain.com/display_whole_page.shtml"><img src="http://www.domain.com/the_file/pictures/<?php echo $f20; ?>" height="50" border="0"></a> <?php $i++; } ?> Hi guys! i got this code: Code: [Select] <? $x = "abcde"; str_split($x); for ($k=0; $k<=119; $k++){ $ax = array($x[0],$x[1],$x[2],$x[3],$x[4]); shuffle($ax); $text = implode("", $ax) . ""; echo $text; echo "<br />"; } ?> if you test it you see that it is working but giving me allot of duplicates results! there is a way to ignore duplicaes while it is runing? thanx. Hi I am using php5 and Mysql I want to generate user id like phone format (Ex: xxx-xxx-xxxx). and check that user id exists in database or not. if yes, i have to generate new user id etc. If that user id not in database, i have to insert user id for new user. Means i have generate unique user id for login purpose. Generating user id is working fine. availability of user id also ok for me by using mysql_num_rows() function. But if user id i exists in database, how can i generate new user id. All this will be done in single instance (When user click on submit button from registration form). Here is my script. Code: [Select] <?php function UserID() { $starting_digit=5; $first_part1=rand(0,99); if(strlen($first_part1)==1) { $first_part="0".$first_part1; } else { $first_part=$first_part1; } $second_part1=rand(1,999); if(strlen($second_part1)==1) { $second_part="00".$second_part1; } elseif(strlen($second_part1)==2) { $second_part="0".$second_part1; } else { $second_part=$second_part1; } $third_part1=rand(1,9999); if(strlen($third_part1)==1) { $third_part="000".$third_part1; } elseif(strlen($third_part1)==2) { $third_part="00".$third_part1; } elseif(strlen($third_part1)==3) { $third_part="0".$third_part1; } else { $third_part=$third_part1; } $userid=$starting_digit.$first_part."-".$second_part."-".$third_part; return $userid; } $random_userid=UserID(); $sql=mysql_query("select * from users where user_id='".$random_userid."'"); if(mysql_num_rows($sql)==0) { $insert=mysql_query("insert into users (user_id) values ('".$random_userid."')"); } ?> If user id not exists in database, that user id inserting in database successfully. If not, empty value is inserting, not generating new user id. Can any one help me out please. Here is my code if(isset($_POST['pass_btn'])) { $numchars = 8; $chars = explode(',','2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z,2,3,4,5,6,7,8,9'); $password=''; for($i=0; $i<$numchars;$i++) { $password.=$chars[rand(0,count($chars)-1)]; } } This is set up so when a person pressing the pass_btn, a password is provided. This works just fine. However, it refreshes the page and clears all other data that user may have entered. Suggestions? 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. This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=345334.0 Hi, Im not sure whether this is a PHP or MySQL question, but im trying to get a select menu to only display the number of options that are defined in the mysql database.
For example
The code I have that retrieves the $quantity from the database.
Lets say that
$quantity = 3
Now I would like the option menu to only display three options, like this:
<select name="quantity"> <option value="<?php echo $quantity ?>"><?php echo 'Maximum of ' . $quantity . ' available'?></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select>but for example, if the $quantity was equal to 10 then I would like the menu to be displayed as such <select name="quantity"> <option value="<?php echo $quantity ?>"><?php echo 'Maximum of ' . $quantity . ' available'?></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> </select>How is it possible to do this? I am completely at a loss here. Many Thanks aquaman Hi all, I want some help regarding my banking project. I have a customer registration form in my project.After successfully completion of the form users have to click on the "Open Account" button.Thereafter a customer id(Auto increment value) should be generated.It was stored in the database where other form details are also being stored. How can i call to this one by one customer id's?? Heshan, Hello everyone, I've been working on this for about 2 days now, and I just can't seem to figure it out so I need some help from someone here. I have a database with three items (will be more, but for now there's three). The database keeps a record of the days that each item is reserved. I want to be able to select and generate a list of items that are available on a specific day. Here is what I have so far: Code: [Select] <?php $result = mysql_query("SELECT `prodid` FROM reservations WHERE `resdate` = '$resdate'") or die (mysql_error()); while ($row = mysql_fetch_row($result)) { $resprodid = $row[0]; $result2 = mysql_query("SELECT `prodid`,`prodname` FROM products"); $row2 = mysql_fetch_row($result2); $prodid = $row2[0]; $prodname= $row2[1]; if ($prodid != $resprodid) { echo $prodid; } } ?> The result that I'm getting are not correct. I either get only one unit listed, or none. Any help would be appreciated. Thanks! Hello, I'm generating a list of questions from a database, say $questions. I'd like to number the questions AFTER I load them from the database (I know that I could enter a number associated with them in the database, but it could get tricky, as the questions will continually be updated and deleted). My question, then, is how can a create a new array which associates each question with a number. Thank you! So I have this function which generates a random serial # that is 12 characters long. However I want to insert a dash every four characters like so: XXXX-XXXX-XXXX Any suggestions? Code: [Select] <?php $serial1 = get_serial_num(12); //Serial # function function get_serial_num($number_cnt){ $ret_arr = array(); $serial = ""; $ser_num = array("1","2","3","4","5","6","7","8","9","0","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"); for($i = 0; $i < $number_cnt; $i++){ $rand = rand(0,count($ser_num)-1); $val = wordwrap($ser_num[$rand],1,"\n", true); $serial .= $val; } return $serial; } echo ''.$serial1.''; ?> Warning: I am a bit noobish. Hello, i made a text site, so you can text from a website. i was making a database of the texted numbers and i found that the mysql line is not inserting the correct number, its going to the max php one. Here the code: if (array_key_exists($carrier, $carriers)) { $correctCarrier = $carriers[$carrier]; $i = 0; while($i < $_POST['amount']){ $i++; $formatted_number = $to.$correctCarrier; $result = ("$i of Your Messages Has been sent to the number ". $_POST['to'] . ".<br>" . mail("$formatted_number", "$subject", "$message") . ""); } mysql_query("INSERT INTO `msgssent` (`number`, `numberofmsg`, `subject`, `message`) VALUES (". $_POST['to'] .", '". $i ."', '". $subject ."', '". $message ."')") Or die(mysql_error()); Echo $result; } i wanted to choose 5 random numbers from 0-20. each number represents an index in an array. is there a way to pick out 5 random items from the array. say if random number generator piked a number 22, the last item in the array is at index 20, it wud then have to go to index 0. thanks! hello, i am trying to see how i can pick a random number between 1-15 and exclude certain numbers. so i have a staff list that once a random number is created it inserts it into the staffnumber field. so the next time i create a random number for a staff, i want to make sure that the random number doesnt select an existing staffnumber. thanks! is there a way to make a random number input into mysql? like if i add a new customer to a table, i want to assign a random number to that customer. Hi Guys I have a code what inserts very simple queries to database, im trying to add a random reference number for each enrty using $reference = rand(111111111111,999999999999); but each time I add an entry it gives me the same random number previously generated for previous entry can you help pleasE? |