Mombu the Php Forum

Go Back   Mombu the Php Forum > Php > control structure for a falied MySQL query?
User Name
Password
REGISTER NOW! Mark Forums Read




Reply
1 22nd October 11:59
External User
 
Posts: 1
Default control structure for a falied MySQL query?



Hello all -

I have an SQL statement that generates a random code number. In the
table definition, the code number has a unique index, so my concern is
that the randomly-generated number could fail the UNIQUE constraint.

What PHP control structure can I use to keep re-trying a query until
it doesn't fail? Most of the time it will successfully insert, and my
guess is that it will only need a second try to generate an unused
number. But, I would like to have bullet-proof code to keep trying the
statement until it doesn't fail.

How could I do this? Here is my sql statement:

INSERT INTO Cards ( code_number ) VALUES ( LPAD( FLOOR( RAND() *
100000 ), 5, '0' ) )
  Reply With Quote


 


2 22nd October 12:00
zeldorblat
External User
 
Posts: 1
Default control structure for a falied MySQL query?



while(true) {
if(mysql_query('insert into cards...'))
break;
}

According to the manual, mysql_query() will return true on success and
false on error -- so just keep doing it until it returns true.

Of course there's no way to guarantee that the query will ever succeed
so you might want to write it so that it eventually gives up:

for($i = 0; $i < 1000; $i++) {
if(mysql_query('insert into cards...'))
break;
}

If it doesn't work after trying 1000 times it will stop.
  Reply With Quote
Reply


Thread Tools
Display Modes




666