PHP - Generate Random Number Unique In A Database
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. Similar TutorialsHow 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. 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 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 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. 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
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++; } ?> 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, im trying to create a website and only now started thinking about the security part(noob mistake). say for example i have home.php page and an index.php page. index.php is where users would sign up/log in. the login and sign up processes are all done but i was thinking of creating a unique id of some sort for when the user logs in. or something like this site (forum.phpfreaks) when we sign in, you are signed but the url stays the same = forums.phpfreaks.com. like if we were signed out we will be permanantly signed out and typing in forums.phpfreaks.com would just land us at the main page where we need to sign in.
right now ,my home.php can be accessed with or without logging in even with sessions.
hope im making sense, thanks in advanced!
**haha that rhymed.
i tried adding:
<?php echo $_SERVER[PHP_SELF] . '?name=' . $userData['name'];?> in the index.php:
<?php ob_start(); session_start(); if(isset($_POST['login'])) { $email = $_POST['email']; $password = $_POST['pass']; require "connection.php"; $emails = mysqli_real_escape_string($con, $email); $query = "SELECT id, name, email, password, salt FROM users WHERE email = '$emails';"; $result = mysqli_query($con, $query); if(mysqli_num_rows($result) == 0) // User not found. So, redirect to login_form again. { echo "<script>alert(\"User does not exist!\")</script>"; } $userData = mysqli_fetch_array($result, MYSQLI_ASSOC); $hash = hash('sha256', $userData['salt'] . hash('sha256', $password) ); if($hash != $userData['password']) { echo "<script>alert(\"Incorrect Password!\")</script>"; }else{ session_regenerate_id(); $_SESSION['sess_user_id'] = $userData['id']; $_SESSION['sess_name'] = $userData['name']; session_write_close(); header('Location: home.php?user='); } } ob_flush(); ?> <!DOCTYPE html> <form name="login" method="post" action="<?php echo $_SERVER[PHP_SELF] . '?name=' . $userData['name'];?>">but i got access forbidden! Edited by noobdood, 19 May 2014 - 10:05 PM. My table looks like this.. `guns_id` int(255) NOT NULL auto_increment, `guns_name` varchar(255) collate latin1_general_ci NOT NULL, `guns_price` int(255) NOT NULL, PRIMARY KEY (`guns_id`) I want to add a product key that is unique through out the whole database as I have other products other than guns aswell. Hi Looking to create an ID which only contains alpha-numeric (no special chars). I looked to generate random bytes and then encode in base64 but base64 contains = + /. The below seems to do it but not sure if bin2hex can return non alpha numeric? bin2hex(openssl_random_pseudo_bytes(18)); Edited December 18, 2018 by mds1256 I'm not sure I'm in the right place, but I'm looking to create a unique URL that links to the same page every time I send an email after a form is submitted on my website and have it expire after 15 days. After expiring, the link would redirect to a default page. I'm still a beginner and realize this is probably going to be a tough task, but any resources or direction provided would be much appreciated. Thanks for the help in advance! 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. 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 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? 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, 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(); } ?> |