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.

Comments

Is the sole purpose of this code to find a free ID in the database? For goodness sake, use autoincrement

Written by rockerest

No it is not, the purpose of my script is purposefull enough to need it working.

Written by phpabuse

Check my solution then :-? and tell me if it works as intended.

Written by Khez

Accepted Answer

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)
    );
Written by Thrustmaster
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki