PHP - Php - Generating Unique Number For Database Field
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 Similar TutorialsHi, Newbie! I need to generate a unique number and put it in a field called "intInstD" value ="123456" to send to Paypoint to initiate an order. They insist each order from my website has a unique number. Can anyone help with a bit of code that does this please? Much appreciated zzdave 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? 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, I'm trying to create a PHP script for user's profile to display the amount of times they've been viewed. I'm looking to have this script increase on a unique view, and it should update the variable in the database. Profiles are accessed by the following link: userprofile.php?userid=X (where X is the ID, e.g. 1, 2, 1001, 345982, etc.). The database variable I'm looking to update is called ProfileViews. I began developing the script, which is as follows: Code: [Select] $_SESSION['Viewed'] = 0; if ($_SESSION['Viewed'] == 0) { $profileViewsQuery = mysql_query("SELECT ProfileViews FROM Users WHERE UserID='????'"); $getProfileViews = mysql_fetch_array($profileViewsQuery); $profileViews = $getProfileViews['ProfileViews']; $profileViews = $profileViews + 1; mysql_query("UPDATE Users SET ProfileViews='$profileViews' WHERE UserID='????'"); $_SESSION['Viewed'] = 1; } However, I'm stumped on a couple things. Could you possibly help me out? 1. How can I get the script to recognize the link accessed's ID? E.g. when a user goes to userprofile.php?userid=1001, how can I get the script to identify the ID to update should be 1001? This is where the "????" would be replaced in the code. 2. On page load, the variable is always going to be $_SESSION['Viewed'] = 0, which isn't going to produce unique hits. Do you have any recommendations how I could achieve unique hits using this method? Thanks very much for reading. Below is my code... I'm new to OOP so forgive me if it's poorly designed. What i'm trying to do is make sure that asset_key never get's duplicated. So when time comes to insert a new record, i can rest assures that asset_key will not duplicate. For some reason $random_number never get's back a value; Code: [Select] <?php class Randomize { function createRN() { $num = rand(100000,999999); $sql = "SELECT * FROM mer_asset_header WHERE asset_key = '$num'"; $go = oci_parse($conn, $sql); oci_execute($go); $count = oci_num_rows($go); if($count = 1) $repeat = Randomize::createRN(); else return $num; } } $random_number = new Randomize; $random_number->createRN(); ?> I should also mention, that if the query finds that asset_key, it should also run createRN() again untill it gets a unique one. Thanks for the help in advance! This topic has been moved to PHP Applications. http://www.phpfreaks.com/forums/index.php?topic=345334.0 Please 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? 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 How to generate a unique random number in php??? Any one who can help me? 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. Good morning! I have a two dimensional array, basically a table (see code below). I want to get a value from the array using two methods: 1) Using the row's key: $NewValue = $MyArray[$UniqueKey]; 2) Using the row's index (row number, so to speak): $NewValue = $MyArray[$RowNumber]; The second print statement in the code below does not work. Both print statements should output the same value. Is there an easy way to do this? The table has hundreds of rows and I will not know the key value of row 879 nor can I generate it. So I cannot use array_keys(). And I DO NOT want to start at the first row and count up to the 879th row. Any clever ideas to share and enlighten? Thanks! <?php // Initialize the array keys and values $MyArray = array(); $MyArray['first']['col1'] = 'abc'; $MyArray['first']['col2'] = 'def'; $MyArray['first']['col3'] = 'ghi'; $MyArray['second']['col1'] = 'jkl'; $MyArray['second']['col2'] = 'mno'; $MyArray['second']['col3'] = 'pqr'; $MyArray['third']['col1'] = 'stu'; $MyArray['third']['col2'] = 'vwx'; $MyArray['third']['col3'] = 'yz'; $MyArray['fourth']['col1'] = 'a1a'; $MyArray['fourth']['col2'] = 'b2b'; $MyArray['fourth']['col3'] = 'c3c'; $MyArray['fifth']['col1'] = 'ddd'; $MyArray['fifth']['col2'] = 'eee'; $MyArray['fifth']['col3'] = 'fff'; // Two methods to get a value. Second one does nothing. print"{$MyArray['third']['col2']}</br>"; print"{$MyArray[2]['col2']}</br>"; ?> Hello everybody,
i try to check if the unique field inventar exists or not before i insert new record.
if the inventar exits the user should get error message.
but i dont know how to do this.
thank you very much for your help.
Rafal
here is my code
<?php include("123.php"); $inventar = $link1->real_escape_string($_POST["inp_inventar"]); $product = $link1->real_escape_string($_POST["inp_product"]); $price = $link1->real_escape_string($_POST["inp_price"]); $link1 = new mysqli("$hoster", "$nameuser", "$password", "$basedata") or die ("Connection Error!"); error_reporting (0); $check_inventar = mysqli_query($link1, "SELECT inventar FROM products WHERE inventar='$inventar'"); $check_inventar_num = mysqli_num_rows($check_inventar); if (isset($_POST['inp_submit']) AND $check_inventar_num = 0) { $query1 = "INSERT INTO products (inventar, product, price) VALUES ('$inventar', '$product', '$price')"; $result1 = $link1->query($query1) or die("Database Error!"); if ($result1 == true) { header ( 'Location:insert.php' ); } } else { echo "there is already product with same inventar id!"; } mysqli_close($link1); ?> 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, 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! 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! Hi there! On a page of mine, random tables get generated. The tables consist of 8 characters, so there's 5 . 10^13 possibilities. Yet ofcourse there is a possibility that 2 tables with the same name can be generated, which ofcourse is not desired. So I need an adjustment that can see whether there is already a name that's the same, and if so, make another random name. And if that one also exists, make a new one again. Untill the name doesn't exist yet and it remains. Here's the script I have right now: function createName($length) { $chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; $i = 0; $password = ""; while ($i <= $length) { $password .= $chars{mt_rand(0,strlen($chars))}; $i++; } return $password; } $name = createName(8); mysql_select_db($database, $con); $sql = "CREATE TABLE " . $name . "( id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), devraag varchar(500), weergave varchar(500), naam varchar(500), inhoud varchar(500), tijd varchar(100))"; mysql_query($sql, $connection)or die(mysql_error()); I'm not goot with the combination of PHP and mysql, and really have no Idea how to do this. Any help? Hello All, I have a contact directory database. It has all the employees of my company (name, phone, email, department, building, etc). Say on one page I have the Marketing Department, and I want to say: "The Marketing Department Director is ________" How would I assign that value from the database? Do I want to put in a unique "keyword" field in the database, but then how would I store all the values automatically on the page? I see pages where I would want to list the Marketing Director, and his secretary, then another page with the Sales Director, and his secretary, etc.... all with being able to change the values in the database, and it changing across all the pages instantly. Do I need to say on every page "select * from database where keyword = marketingdirector" and then store that result as a variable? It seems unpractical to repeat that a few times for each different person I want to list. Is there a better way to do this then I'm thinking? Thanks all! I have a code to sum up a field called quantityHand in MySQL, in my example below, the value always return 40 as a positive number instead of 40.00- 0.00 0.00 40.00- I have used intval() or floatval() function to convert the type of variable from string to int/float but still not working. Any help please? Here is the code Code: [Select] $sql = mysql_query("SELECT DISTINCT itemNumber, itemDesc, quantityHand, SUM(quantityHand) AS quantityHand FROM inventory where itemNumber like '%$term%' GROUP BY `itemNumber` ORDER BY `itemNumber`"); while ($row = mysql_fetch_array($sql)){ echo "<b>"; echo "</td><td style=\"text-align: center;\"><b>"; echo $row['itemNumber']; echo "</td><td style=\"text-align: center;\"><b>"; echo $row['itemDesc']; //echo "</td><td style=\"text-align: right;\">"; echo "</td><td style=\"text-align: center;\"><b>"; echo $row ['quantityHand']; echo "</td></tr>"; echo "</b>"; I have a mysql table which will store users email addresses (each is unique and is the primary field) and a timestamp. I have added another column called `'unique_code' (varchar(64), utf8_unicode_ci)`. What I would very much appreciate assistance with is; a) Generating a 5 digit alphanumeric code, ie: 5ABH6 b) Check all rows the 'unique_code' column to ensure it is unique, otherwise re-generate and check again c) Insert the uniquely generated 5 digit alphanumeric code into `'unique_code'` column, corresponding to the email address just entered. d) display the code on screen. What code must I put and where? **My current php is as follows:** Code: [Select] require "includes/connect.php"; $msg = ''; if($_POST['email']){ // Requested with AJAX: $ajax = ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'); try{ if(!filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL)){ throw new Exception('Invalid Email!'); } $mysqli->query("INSERT INTO coming_soon_emails SET email='".$mysqli->real_escape_string($_POST['email'])."'"); if($mysqli->affected_rows != 1){ throw new Exception('You are already on the notification list.'); } if($ajax){ die('{"status":1}'); } $msg = "Thank you!"; } catch (Exception $e){ if($ajax){ die(json_encode(array('error'=>$e->getMessage()))); } $msg = $e->getMessage(); } } |