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 开发者_JAVA技巧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.
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) );
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.
Several things
- It is not using mysql_query.
- It is not fetching the result of the query (which doesn't exist)
- count is a built in PHP method, not a number.
- 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)
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
精彩评论