I am trying to generate a random 10 digit number and insert this into mysql on page load, so each time the page refreshes or loads there should be a different 10 digit number being inserted into the database, however at the moment it just keeps inserting the same 10 digit number again and again.
Can someone please show me where I am going wrong? Thanks.
<?php
session_start();
$db_hostname = 'localhost';
$db_database = 'hewden1';
$db_username = 'root';
$db_password = '';
$db_server = mysql_connect($db_hostname, $db_username, $db_password)
or die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
$num0 = (rand(10,100));
$num1 = date("Ymd");
$num2 = (rand(100,1000));
$num3 = time();
$randnum = $num0 . $num1 . $num2 . $num3;
$sql="INSERT INTO supplier_session (session_number)
VALUES ('$randnum')";
$result = mysql_query($sql);
?>
This is the number I am constantly getting: 2147483647
One simple method is to make use of RAND() function available in SQL Server. RAND() function simply generate a decimal number between 0 (inclusive) and 1 (exclusive). The logic is to multiply value returned by RAND() by 1 billion so that it has enough digits and apply LEFT function to extract 6 digits needed.
The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.
RAND() Return a random floating-point value.
In SQL Server there is a built-in function RAND() to generate random number. RAND() will return a random float value between 0 to 1.
try to getting ten digit rand no
$randnum = rand(1111111111,9999999999);
You need to change column type. The number that you try to insert is higher than column maximum value (in your case SIGNED INT - 2147483647)
SIGNED INT - 2147483647
UNSIGNED INT - 4294967295
SIGNED BIGINT - 9223372036854775807
UNSIGNED BIGINT - 18446744073709551615
You're getting 2147483647
because it's the highest signed 32 bit integer that exists (binary it's 1111111111111111111111111111111
). This is also the contents of the constant PHP_INT_MAX
.
Just use a string with a loop and the mt_rand()
function:
<?php
for ($randomNumber = mt_rand(1, 9), $i = 1; $i < 10; $i++) {
$randomNumber .= mt_rand(0, 9);
}
var_dump($randomNumber); //eg. string(10) "9152676628"
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With