Reputation: 193
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
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
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:
create table myTABLE (
id integer aut_increment,
username varchar(128),
email varchar(128),
..
primary key(id)
);
Upvotes: 2
Reputation: 82078
Several things
Upvotes: 0
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