- Random Number Generation in Mysql PHP
- Random Number Generation in Mysql PHP
- Php random mysql data
- Create many rows in Mysql with php random number generator
- How to insert random number into database no repeat
- Approach A
- Approach B :
- Approach C
- Approach D
- how to select random and unique records from mysql (in php language)
- 2 Answers 2
- Generate Random Password Using PHP And MySQL
- To Generate Random Password It Takes Only three Steps:-
- Step 1. Make a HTML file and define markup and scripting
- Step 2. Make a PHP file to generate random password and do signup
- Step 3. Make a CSS file and define styling
Random Number Generation in Mysql PHP
Solution 2: You can create an array holding all the numbers you have previously inserted and compare your current number to whats in the array: Solution 1: For unique random number you can use below function. Solution 2: Store all the values which you want to show in random in a variable, use rand() http://php.net/manual/en/function.rand.php and shuffle() http://php.net/manual/en/function.shuffle.php to make the random data and display them Solution 3: there are several methods to get random data from db in php another method: — one more method:- Solution 1: This is just a quick example, way overkill, you would probably need 1 line in the random section.
Random Number Generation in Mysql PHP
With what you specified, this does not seem possible.
You require 16,000,000 unique numbers from a given 8 digit number, of which the leading 2 is 01 .
That leaves you with only 6 numbers , so your range will be 1,000,000 numbers
from 01000000 to 01999999 .
This does not seem correct at all.
John, regarding your comment to pavium, if you need all the numbers to have exactly the same length but not necessarily random you can make use of the ZEROFILL MySQL property along with the auto_increment index.
PHP Code to generate random ID number for database, You could change the AUTO_INCREMENT seed for the PRIMARY KEY of your table to get an initially greater number.. CREATE TABLE example ( nid INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50) ) AUTO_INCREMENT = 200000; The next value generated for nid when inserting …
Php random mysql data
All those telling you to use rand in the SQL query have not read the question. To those people: the asker wants a random combination of data from the rows, not a random row.
Something like this. It will take all the results from the database and echo a totally random combination. I couldn’t avoid using arrays as they are super useful.
// Close the database connection mysql_close(); // Max rand number $max = count($rows) - 1; // print out random combination of data. echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][1] . " " . $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " " . $rows[rand(0, $max)][4] . " " . $rows[rand(0, $max)][5]; ?>
Store all the values which you want to show in random in a variable, use rand() http://php.net/manual/en/function.rand.php and shuffle() http://php.net/manual/en/function.shuffle.php to make the random data and display them
there are several methods to get random data from db in php
SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;
$range_result = mysql_query( " SELECT MAX(`id`) AS max_id , MIN(`id`) AS min_id FROM `table` "); $range_row = mysql_fetch_object( $range_result ); $random = mt_rand( $range_row->min_id , $range_row->max_id ); $result = mysql_query( " SELECT * FROM `table` WHERE `id` >= $random LIMIT 0,1 ");
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `table` "); $offset_row = mysql_fetch_object( $offset_result ); $offset = $offset_row->offset; $result = mysql_query( " SELECT * FROM `table` LIMIT $offset, 1 " );
PHP/MySQL — Best way to create unique random string?, Luckily databases already have the ability to create unique IDs (numeric) — I suggest the approach that we took, which is to create a two-way conversion between a gently increasing numeric ID and an alpha-numeric ID. Having it be two-way assures that the alpha-numeric «random» versions are also unique …
Create many rows in Mysql with php random number generator
This is just a quick example, way overkill, you would probably need 1 line in the random section. But it is all I have at the moment and have to head out.
create schema so_gibberish; -- creates database use so_gibberish; -- use it -- drop table random; -- during debug create table random ( id int auto_increment primary key, question varchar(50) not null, category int not null, randomOrder int not null, key (category) );
Create a stored procedure to insert random questions (with a ? at end) Creates 300 at a time when you call it
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx DELIMITER $$ drop procedure if exists createRandomQuestions$$ -- 17 categories of questions randomly created. yes random word questions and categories. create procedure createRandomQuestions() BEGIN set @i=1; WHILE @i
call createRandomQuestions();
You can create an array holding all the numbers you have previously inserted and compare your current number to whats in the array:
$inserted_numbers = array() if( in_array( $number, $inserted_numbers ) ) < // The numbers is already in the array >else < // NUmber not in array, do stuff array_push( $inserted_numbers, $number ) >
“how to created random varchar number in php” Code, “how to created random varchar number in php” Code Answer. how to create random alphanumeric in php . php by Mr. Samy on Jul 02 2020 Comment . 8 Add a Grepper Answer . PHP answers related to “how to created random varchar number in php”
How to insert random number into database no repeat
For unique random number you can use below function.You can pass length as you want.
public static function generateUniqueId($length = 7) < $salt = "abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789"; srand(); // start the random generator $userId = ""; // set the inital variable for ($i = 0; $i < $length; $i++) < // loop and create userId $userId .= substr($salt, rand() % strlen($salt), 1); >return $userId; >
Approach A
(Best in my opinion) As Wreigh suggested, it's better to use an auto-increment field, it covers it all for you, so you don't have to worry about this things.
For this, try this MySQL command. ALTER TABLE Users MODIFY COLUMN user_id INT auto_increment . After that, you can just insert the other fields and user_id will always be unique:
$query = "INSERT INTO Users (user_type, name, lastname, email, phone, address, apt, city, state, zip, username, password) VALUES ('parent','$name', '$lastname', '$email', '$phone', '$address', '$apt', '$city', '$state', '$zip', '$username', '$hash')"; $result = mysqli_query($query);
Approach B :
inserting the next id available:
$query = "INSERT INTO Users (user_id, user_type, name, lastname, email, phone, address, apt, city, state, zip, username, password) SELECT max(user_id)+1,'parent','$name', '$lastname', '$email', '$phone', '$address', '$apt', '$city', '$state', '$zip', '$username', '$hash' from Users"; $result = mysqli_query($query);
Look what I did: I used INSERT (fields) SELECT , without VALUES . That will insert the id at the same time it reads. This requires user_id to be numeric.
Approach C
(as I saw you use quotes for user_id, maybe it's a string field)
1) If user_id is string, generate an very-likely unique id using uniqid()
Gets a prefixed unique identifier based on the current time in microseconds.
2) Then, just to be sure, check if it's not used.
It will keep trying until id is really unique. This requires user_id to be string field, like varchar, since uniqid() returns letters AND numbers.
Approach D
1) If user_id is integer, generate an very-likely unique id using rand()
rand — Generate a random integer
2) Then, just to be sure, check if it's not used.
Php random mysql data, All tables are set to VARCHAR. I want to use php on a web page to call random data from each row, eg mix and match row1 FirstName with row3 SecondName and row2 Sentence1 etc. I read it is quicker to randomise using php but I really can't grasp how to do this despite searching. I can connect to my …
how to select random and unique records from mysql (in php language)
Now i want to make a quiz where there will be 15 questions from these 150 questions and each question will be randomly selected from the pool of these 150 questions and also all these 15 questions must be unique i have used the followig approach but with this approach i am getting random question but there is a possibility of 2 same questions.
$n1=mt_rand(1,150); $q=mysqli_query($mysqli,"select * from quiz WHERE qno = '".$n1."'");
I have also try to use DISTINCT but with this also I get two or more same questions:-
$n1=mt_rand(1,150); $q=mysqli_query($mysqli,"select DISTINCT qno,ques,a,b,c,d,ans from quiz where qno='".$n1."' " );
2 Answers 2
Preliminary: I assume this is your table:
CREATE TABLE questions ( question_number INTEGER NOT NULL PRIMARY KEY, question VARCHAR(255) NOT NULL, answer_a VARCHAR(255) NOT NULL, answer_b VARCHAR(255) NOT NULL, answer_c VARCHAR(255) NOT NULL, answer_d VARCHAR(255) NOT NULL, right_answer ENUM ('a', 'b', 'c', 'd') NOT NULL ) ;
You can let MySQL do the hard work for you, and just execute the following SELECT statement, that will sort randomly all your table (i.e.: it is actually shuffling the rows), and just choose the top 5 rows (NOTE: I've used 5 instead of 15 for the sake of simplicity).
The key point: instead of generating a random number from PHP, let the database deal with the random numbers.
SELECT question_number, question, answer_a, answer_b, answer_c, answer_d, right_answer FROM questions ORDER BY rand() LIMIT 5 ;
(Converting this to PHP code is quite straightforward)
You will get something like:
question_number | question | answer_a | answer_b | answer_c | answer_d | right_answer --------------: | :--------------------------------------------------- | :----------- | :----------- | :----------------- | :---------------------- | :----------- 2 | Which is the colour of the White HOuse? | Black | Green | Blue | White | d 3 | What's the tallest building on Earth as of 2017? | Empire State | Burj Khalifa | Eiffel Tower | Tokyo Skytree | b 8 | Does 1 kg of lead weight more than 1 kg of feathers? | Yes | No | Depends on gravity | Depends on kind of bird | b 6 | Which is the third letter of the alphabet? | a | b | c | d | c 7 | Which is the first vowel? | a | e | i | o | a
Repeating the same query will give you a different set of questions (although some might have already be asked):
question_number | question | answer_a | answer_b | answer_c | answer_d | right_answer --------------: | :--------------------------------------------------- | :------- | :------- | :----------------- | :---------------------- | :----------- 9 | How many primary colours are there (for a human)? | 3 | 2 | 6 | 4 | a 5 | How many wheels does a (most common) car have? | 4 | 6 | 8 | 10 | b 8 | Does 1 kg of lead weight more than 1 kg of feathers? | Yes | No | Depends on gravity | Depends on kind of bird | b 2 | Which is the colour of the White HOuse? | Black | Green | Blue | White | d 6 | Which is the third letter of the alphabet? | a | b | c | d | c
When you work with a database, it is normally a good idea to let the database give you the complete answer to your problem, instead of looping in your code.
You can see all the setup and some more executions at dbfiddle here
Generate Random Password Using PHP And MySQL
Password is always be at the most risk because if your password is not strong then someone can steal your account and access all your details.
Your password should have to be strong to prevent account stealing so it will be tougher to crack your password.
So, in this tutorial we will show you how to generate strong random password using PHP and MySQL.
To Generate Random Password It Takes Only three Steps:-
- Make a HTML file and define markup and scripting
- Make a PHP file to generate random password and do signup
- Make a CSS file and define styling
Step 1. Make a HTML file and define markup and scripting
We make a HTML file and save it with a name random_password.html
Random Password Generator
In this step we create a form to enter details by user and send it to 'generate_password.php' file to generate password and do signup.
Always validate data before form submitting you can view our form validation using jquery tutorial to see how to validate data.
Step 2. Make a PHP file to generate random password and do signup
We make a PHP file and save it with a name generate_password.php
// Database Structure CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` text NOT NULL, `email` text NOT NULL, `password` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1 ?>
In this step we create a database table called 'users' to store user details and then get name and email entered by user and then generate random password by writting alphanumeric string and using str_shuffle() function to get strong and random password.
Aafter that we store all the details in table and display the password to user you can also send email to user email id having password in email message instead of displaying in form.
Step 3. Make a CSS file and define styling
We make a CSS file and save it with a name random_password_style.css
body < margin:0 auto; padding:0px; text-align:center; width:100%; font-family: "Myriad Pro","Helvetica Neue",Helvetica,Arial,Sans-Serif; background-color:#9FA3C9; >#wrapper < margin:0 auto; padding:0px; text-align:center; width:995px; >#wrapper h1 < margin-top:50px; font-size:45px; color:#4C3866; >#wrapper h1 p < font-size:18px; >#signup_form < background-color:white; width:270px; margin-left:345px; box-shadow:0px 0px 15px 0px #4C3866; padding:15px; >#signup_form #signup_label < color:#4C3866; margin:0px; padding-bottom:10px; margin-bottom:30px; font-size:25px; border-bottom:1px solid #E6E6E6; >#signup_form input[type="text"] < width:230px; height:35px; padding-left:10px; font-size:16px; margin-bottom:15px; border:1px solid #D8D8D8; color:#585858; >#signup_form input[type="submit"]
You can also view our check password strength using jQuery to check the strongness of your generated password.
That's all, this is how to generate random and strong password using PHP and MySQL. You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.