phpabuse
phpabuse

Reputation: 193

PHP MySQL while loop

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.

Upvotes: 2

Views: 1127

Answers (4)

Khez
Khez

Reputation: 10350

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

Upvotes: 0

UltraInstinct
UltraInstinct

Reputation: 44474

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)
    );

Upvotes: 2

cwallenpoole
cwallenpoole

Reputation: 82078

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)

Upvotes: 0

Demian Brecht
Demian Brecht

Reputation: 21378

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.

Upvotes: 1

Related Questions