我有一个移动应用程序,请求服务器中的密钥,密钥结构包含7个字符,如下所示:
@ + [0-9] + [0-9] + [0-9] + [A-Z] + [A-Z] + [0-9]
@876EU8, @668KI2 .......
密钥最初有七个字符,在这种情况下为三个数字,两个字母和一个数字,通过数学计算得出最多为676,000个密钥。
为了使这些密钥更好,我在PHP中使用了以下代码:
function generateRandomString($length = 2) {
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$randomKeyNumber = rand(100,999);
$randomKeyLetter = generateRandomString();
$randomKeyLast = rand(0,9);
$randomKey = "#".$randomKeyNumber.$randomKeyLetter.$randomKeyLast;//Returns a key like @876TG9
下一个代码检查密钥是否存在于数据库中;如果存在,则随机分配另一个密钥;如果不存在,则将其插入数据库并将此密钥返回给我的应用程序
该代码可以完美地工作,但是假设系统已经生成了总共650,000个密钥,那么在此代码的情况下,它将始终生成相同的密钥,并且生成不存在的密钥的可能性很小。
如何解决此问题并避免将来出现问题?(按顺序创建密钥是没有问题的,例如000AA0、000AA1、000AA2、000AA3 .... 999ZZ9)
您可以做的是使用已添加的所有键PDO::query()
发出一个SELECT COUNT(*)
或简单的SELECT *
语句,然后使用PDOStatement :: fetchColumn()检索将返回的行数(即,在这种情况下,所有他们)
这是一个手动示例
<?php
$sql = "SELECT COUNT(*) FROM Keys";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
$res = null;
$conn = null;
?>
这是您所需的代码:
<?php
$sql = "SELECT * From Keys";
if ($res = $conn->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* and then you get the id of the last one on the list, and to that one you add 1 */
$last_id = $conn->lastInsertId();
$new_id = $last_id + 1;
/* then you insert that in some place inside the key itself, that way you don't need to worry than two keys can be equal */
}
else {
/* No rows matched, just create a key and add to the database here */
}
}
¿>
或者,您可以将查询SELECT语句与PDO中的countRows结合使用,它在便携式应用程序和/或数据库中并非始终有效,但就像我们对您的应用程序一无所知,我们不知道是否会工作的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句