2

Why doesn't this code work?

It creates a random number, if it exists in database then it generates a new one until it can insert into the unique key, if not then it inserts straight away into database.

$id;
    do {
    $id = mt_rand(1, 10);
    "SELECT count(*) FROM accounts WHERE id = '$id'";
    } while (count != 0);

    $sql = "INSERT INTO accounts (id, username, email, password, sex)
    VALUES ('$id', '$username', '$email', '$password', '$sex')";

The reason the mt_rand is low for testing purposes.

2
  • No it is not, the purpose of my script is purposefull enough to need it working. Commented Apr 2, 2011 at 3:44
  • Check my solution then :-? and tell me if it works as intended. Commented Apr 2, 2011 at 3:50

4 Answers 4

2

That is because, you are not really firing a mySQL query. You just have the query string as such. You must pass the string the mysql_query(..). Retrieve the resource, and then check out the final number of rows.

Method #1: (modifying your code)

$id;$count;
do {
    $id = mt_rand(1, 10);
    $res = mysql_query("SELECT count(*) as c FROM accounts WHERE id = '$id'");
    $row = mysql_fetch_array($res);
    $count = $row['c'];
} while ($count != 0);

$sql = "INSERT INTO accounts ...";
//..

Method #2:

  • Modify your MySQL table, use an auto_increment. Create a table this way
  • create table myTABLE (
        id integer aut_increment,
        username varchar(128),
        email varchar(128),
        ..
        primary key(id)
    );
Sign up to request clarification or add additional context in comments.

Comments

1

Why are you going about generating an ID using this method? Why wouldn't you just use an auto-incrementing ID?

CREATE TABLE accounts (
     id INT NOT NULL AUTO_INCREMENT,
)

Generating an ID using using mt_rand doesn't make a whole lot of sense and will be incredibly expensive with the more accounts that you get.

Comments

0

Several things

  1. It is not using mysql_query.
  2. It is not fetching the result of the query (which doesn't exist)
  3. count is a built in PHP method, not a number.
  4. You should not be having that many round trips to the database (it is a very bad idea to generate a random identifier that way)

Comments

0

Erm... there seems to be some mild issues in that code:

$id;
do {
    $id = mt_rand(1, 10);
    $c=mysql_query('SELECT id FROM accounts WHERE id = '.$id.' LIMIT 1;');
}while(mysql_num_rows($c)!=0);

P.S. You should consider looking into: uniqid in the PHP manual and auto-incrementing an sql field

1 Comment

this query always returns 1 row, the limit and the mysql_num_rows are pointless

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.