How can I generate 100 records with 5 random characters and insert into the database with a query.
I want to insert into this table:
codes
id (auto-increment)
codes
How can I generate 100 records with 5 random characters and insert into the database with a query.
I want to insert into this table:
codes
id (auto-increment)
codes
Try this one -
SELECT CONCAT(
CHAR( FLOOR(65 + (RAND() * 25))),
CHAR( FLOOR(65 + (RAND() * 25))),
CHAR( FLOOR(65 + (RAND() * 25))),
CHAR( FLOOR(65 + (RAND() * 25))),
CHAR( FLOOR(65 + (RAND() * 25)))
) random_string;
This query generates ASCII codes from 'A' to 'Z' and generates a random string from them. I cannot say that this way is elegant, but it works;-)
INSERT INTO codes_tbl (codes) VALUES (SUBSTRING(MD5(RAND()) FROM 1 FOR 5));
That should take care of it.
md5
gives you a string that only includes hex digits so the codes will be quite limited.
Commented
Nov 21, 2011 at 5:05
INSERT INTO codes_tbl (codes) VALUES (SUBSTRING(MD5(RAND()) FROM 1 FOR 5));
In MySql U Can Do It Like This
insert into table ( SUBSTRING(MD5(RAND()) FROM 1 FOR 10) , field2 , field3) , ( SUBSTRING(MD5(RAND()) FROM 1 FOR 10) , field2 , field3) , .........
If You Want to Do it With Php. U Can Check This Link
Further You can Check The Following Questions Already asked at Stackoverflow
Could you try this out?:
CREATE DEFINER=`root`@`localhost` PROCEDURE `InsertOneHundredRandomCodes` ()
BEGIN
DECLARE ctr INT DEFAULT 0;
hundred_loop:LOOP
SET ctr = ctr + 1; -- increment
-- insert command here
INSERT INTO codes (codes)
SELECT SUBSTRING(MD5(RAND()) FROM 1 FOR 5) AS codes;
IF ctr = 100 THEN -- check if we should stop
LEAVE hundred_loop;
END IF;
END LOOP hundred_loop;
END//
Create that procedure then run this command:
CALL InsertOneHundredRandomCodes();
It should insert into codes
100 random values for the codes
value.