Re: parallel execution of php code?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Martin van den Berg <martinvdberg@xxxxxxxxx> writes:

> I have this piece of php-code which inserts data into a database.
> Before inserting it must verify if the data is unique. The php code
> looks something like:
> 
> $query = "SELECT id FROM mytable WHERE bla LIKE " . $x .";
> $rows = execute( $query )
> if ( $rows == 0 )
> {
>    /* some more processing */
>   $query = "INSERT INTO mytable ...... etc etc
>   execute( $query )
> }
> 
> Now here is the problem: when the user enters the page, and directly
> refreshes the record is inserted twice.... Is is possible that both
> requests are processed simulatiounsly by the server (apache on linux)?
> And can I add something like a critical section or semaphore to
> overcome this problem.
> 

There are 2 ways to handle this problem -

- create a UNIQUE index on whatever columns you want to be unique in
  your database.  This way, when the user refreshes the page, the second
  insertion will fail.  Of course, it means you will need to handle the
  "duplicate key" error that the database will throw up gracefully.

- When the page loads, check if the $_SESSION["_insert_success"] is
  set.  If not, then do the insert part and if the insert is successful,
  set $_SESSION["_insert_success"]=true.  If the variable is set, then
  do not do the insert part , simply display the page again.
-- 
Raj Shekhar		           
blog : http://rajshekhar.net/blog  home : http://rajshekhar.net
Disclaimer : http://rajshekhar.net/disclaimer 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux