1

我正在尝试编写一个函数来检查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
4

2 回答 2

1

为什么不使用AUTO_INCREMENT列而不是尝试生成“随机”ID?此外,EventId函数也不安全,因为选择一个 id 并将其存储在数据库中不是原子的,因此另一个进程可能已经使用了相同的 id。

如果表具有event_id创建为INT AUTO_INCREMENTSQL 的列,则应如下所示:

INSERT INTO foo (event_id, ...) VALUES (<everything EXCEPT event_id>);
event_id = SELECT LAST_INSERT_ID();
于 2013-03-17T02:40:40.447 回答
0

您没有说明为什么是not working,但我的猜测是,在//insert into events table下面的代码中,您正在使用$newEventIdin INSERT,并且如果最初的$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..");
于 2013-03-16T21:55:48.483 回答