1

I'm trying to write a function that checks if a random number exists in 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
10
  • 3
    Ok. What specifically is the question? Commented Mar 16, 2013 at 21:39
  • @UnholyRanger the question is in the title. But what does EventId() do/mean? Commented Mar 16, 2013 at 21:40
  • What's with the break statement after the if? It makes no sense. And it seems like you're missing an opening {. Commented Mar 16, 2013 at 21:42
  • @MathieuImbert No. All braces are correct. Commented Mar 16, 2013 at 21:45
  • ITT, How do you know that the function is not working? Commented Mar 16, 2013 at 21:46

2 Answers 2

1

Why not using AUTO_INCREMENT column instead trying to generate "random" id? Also, EventId function is not safe as choosing a id and storing it in database is not atomic so another process may already used same id.

If table has event_id column created as INT AUTO_INCREMENT SQL should look like this:

INSERT INTO foo (event_id, ...) VALUES (<everything EXCEPT event_id>);
event_id = SELECT LAST_INSERT_ID();
Sign up to request clarification or add additional context in comments.

Comments

0

You don't state why it's not working, but my guess is that in //insert into events table code below your are using the $newEventId in the INSERT, and it works fine if the initial $newEventId causes (mysql_num_rows(mysql_query("SELECT id FROM events WHERE EventID=$gen" )) == 0) to return true, but not if it returns true on the recursive function.

Try returning the value on the break and using that instead of $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..");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.