Generating Unique Random Numbers for Database Inserts
The core issue in your current implementation stems from a misunderstanding of how PHP variables behave during page execution versus session storage. You are observing the constant value 2147483647 because this is the maximum value for a signed 32-bit integer in many PHP configurations, caused by integer overflow.
In your code, you concatenate random numbers and timestamps to create $randnum. However, the logic fails before that concatenation even happens reliably. The primary culprit is the use of the deprecated mysql_* functions combined with a critical flaw in how you are attempting to generate the randomness. While rand() generates a pseudo-random number, relying solely on it for high-precision identifiers without seeding or specific range constraints can lead to collisions or overflow issues if not handled carefully within integer limits.
More importantly, the code provided executes every time the page loads. If your goal is to insert a unique number per page load, the logic in your snippet actually attempts this. However, the result of 2147483647 indicates that the arithmetic operations exceeded the maximum limit of a standard integer. In PHP, mixing large numbers (like timestamps) with random integers can trigger floating-point conversion issues or overflow into the signed integer ceiling.
The Integer Overflow Trap
The value 2147483647 is $2^{31} - 1$. This is the hard limit for a signed 32-bit integer. When you run:
$num0 = (rand(10,100));
$num1 = date("Ymd"); // e.g., "20231027"
$num2 = (rand(100,1000));
$num3 = time(); // Returns Unix timestamp
If your PHP configuration treats these as integers and performs arithmetic or concatenation in a way that triggers integer context, the result can cap at the maximum integer value. The time() function returns a large integer (often exceeding 2 billion in modern years). If $randnum is treated as an integer during the concatenation process due to implicit type coercion in older PHP versions or specific configurations, it will overflow.
To generate a true random 10-digit number without hitting this ceiling, you must treat the result as a string or use a range that fits within a safe integer boundary. A safer approach using rand() involves generating a number strictly within the desired 10-digit range (1,000,000,000 to 9,999,999,999).
// Generate a random number between 1 billion and 9.999 billion
$randomNumber = rand(1000000000, 9999999999);
// Ensure it is treated as a string to prevent overflow issues during storage
$sessionNumber = (string)$randomNumber;
Modernizing the Database Connection
Your current script uses mysql_connect, mysql_select_db, and mysql_query. These functions were deprecated in PHP 5.5.0 and removed in PHP 7.0.0. Continuing to use them will result in fatal errors on any modern server environment.
To resolve this, you should migrate to mysqli or PDO. Below is a robust example using PDO, which supports prepared statements to prevent SQL injection vulnerabilitiesâa significant security risk when inserting user-generated data like session numbers.
<?php
session_start();
try {
// Establish connection using PDO
$pdo = new PDO(
"mysql:host=localhost;dbname=hewden1;charset=utf8mb4",
"root",
"",
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
// Generate a safe, random 10-digit number
// We cast to string immediately to ensure no integer overflow occurs
$sessionNumber = (string)rand(1000000000, 9999999999);
// Prepare the statement
$stmt = $pdo->prepare("INSERT INTO supplier_session (session_number) VALUES (:session_number)");
// Execute with parameters
$stmt->execute([
':session_number' => $sessionNumber
]);
echo "New session number generated and inserted.";
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
Handling Duplicate Keys
When inserting random numbers into a database, there is a non-zero probability of generating the same number twice in rapid succession. If your supplier_session table has a primary key or unique constraint on session_number, attempting to insert a duplicate will trigger a constraint violation error (e.g., Duplicate entry '1234567890' for key 'PRIMARY').
To handle this gracefully, you should catch the exception during insertion and regenerate the number if a collision occurs. This ensures your application remains functional even under high load where collisions become more frequent.
$sessionNumber = (string)rand(1000000000, 9999999999);
$maxAttempts = 5; // Safety limit to prevent infinite loops
for ($i = 0; $i < $maxAttempts; $i++) {
try {
$stmt->execute([':session_number' => $sessionNumber]);
break; // Success, exit loop
} catch (PDOException $e) {
if ($i === $maxAttempts - 1) {
throw new Exception("Failed to generate a unique session number after maximum attempts.");
}
// Regenerate number on collision
$sessionNumber = (string)rand(1000000000, 9999999999);
}
}
Conclusion
The constant output of 2147483647 was a symptom of integer overflow caused by mixing large timestamps with random integers. By generating the number within a safe numeric range and treating it as a string, you eliminate this risk. Additionally, upgrading from the deprecated mysql_* functions to PDO is essential for maintaining compatibility and security in modern PHP applications.