Why PHP sends queries to the database out of order?

In General, faced with such a problem. There is a piece of code:
$validation = Booking::findByUserProduct( $user_id, $product_id );
$answer = Booking::queryAddReturn($validation, $product_id, $way, $user_id, $count);

It is passed the parameters to record in the database. First there is a check that is not recorded whether the information in the database, to avoid duplicates. If so, $validation equals false, otherwise - true. Then a request is sent (in the method of Booking::queryAddReturn ). It processed $validation, depending on an entry is created or not. Along with this, the user will receive appropriate message.

What's the problem: I have the feeling that php gives to the first the second request (write to DB), and then first (to check existence of record). If I remove the second line, then var_dump($validation) gives bool(true), i.e. there is no record. If I can get it back, then bool(false).

Code Booking::findByUserProduct:
public static function findByUserProduct( $user_id, $product_id ) {
 $sql = 'SELECT * FROM booking WHERE `user_id`=:user_id AND `product_id`=:product_id';
 $res = \Yii::$app->db->createCommand($sql)
 ->bindValue(':user_id', (int) $user_id)
 ->bindValue(':product_id', (int) $product_id)
 return count($res) === 0;

Code Booking::queryAddReturn:
public static function queryAddReturn($validation, $product_id, $way, $user_id, $count) {

 if( $validation !== true ) {
 return '<p class="text-light">Error: item has been ordered</p>';
 if( Booking::addOne( $product_id, $way, $user_id, $count ) )
 return '<p class="text-light">Order received successfully</p>';

 return '<p class="text-light">Error: failed to process request</p>';

And in findByUserProduct var_dump($res) produces an array with the values $user_id and $product_id was passed.

What could be the reason?
June 7th 19 at 14:28
2 answers
June 7th 19 at 14:30
Well, if you want to have everything in order, then use transactions. I your code is not very looked. but the essence of the transaction is that it blocks other operations until the query is executed.
June 7th 19 at 14:32
Turned out to be. it was all due to the fact that client-side code is called twice. More precisely, one button per click was assigned two of the same processor. Ajax request went twice.

Find more questions by tags PHPSQL