我正在尝试编写一个函数来检查mysql中是否存在随机数
$newEventId = rand(1000, 10000);
EventId($newEventId);
function EventId($gen)
{
if (mysql_num_rows(mysql_query("SELECT id FROM events WHERE EventID=$gen" )) == 0)
break;
// recall function
else
{
$newEventId = rand(1000, 10000);
EventId($newEventId);
}
}
//insert into events table发布于 2013-03-17 10:40:40
为什么不使用AUTO_INCREMENT列来生成“随机”id呢?此外,EventId函数是不安全的,因为选择一个id并将其存储在数据库中不是原子的,因此另一个进程可能已经使用了相同的id。
如果表具有创建为INT AUTO_INCREMENT的event_id列,则SQL应如下所示:
INSERT INTO foo (event_id, ...) VALUES (<everything EXCEPT event_id>);
event_id = SELECT LAST_INSERT_ID();发布于 2013-03-17 05:55:48
您没有说明它为什么是not working,但我猜在下面的//insert into events table代码中,您在INSERT中使用了$newEventId,如果初始$newEventId导致(mysql_num_rows(mysql_query("SELECT id FROM events WHERE EventID=$gen" )) == 0)返回true,则它工作得很好,但如果它在递归函数上返回true,则不是这样。
尝试返回break上的值并使用该值而不是$newEventId
function EventId($gen)
{
if (mysql_num_rows(mysql_query("SELECT id FROM events WHERE EventID=$gen" )) == 0) {
return $gen; // return the number that will be set as $EventId and used in the insert
break;
}
// recall function
else
{
$newEventId = rand(1000, 10000);
EventId($newEventId);
}
}
$newEventId = rand(1000, 10000);
$EventId = EventId($newEventId); // set the returned $gen to $EventId to be used in the Insert query
//insert into events table
mysql_query("INSERT INTO events ... EventID=$EventId..");https://stackoverflow.com/questions/15454960
复制相似问题