D
D
Diman Suvorkin2018-03-03 21:26:48
PHP
Diman Suvorkin, 2018-03-03 21:26:48

Why is PHP sending database queries out of order?

In general, I faced 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);

Parameters for writing to the database are passed to it. First, a check is made to see if the information is recorded in the database so that there are no duplicates. If it is, then $validation is false, otherwise it is true. The request is then sent (in the Booking::queryAddReturn method). $validation is processed in it, depending on it the record is created or not. Along with this, the user is given a corresponding message.
What is the problem: it seems that php first gives the second request (to write to the database), and then the first one (to check for the existence of the record). If I remove the second line, then var_dump($validation) produces bool(true), that is, there is no entry. If I return it, 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)
      ->queryall();
  return count($res) === 0;
}

Booking::queryAddReturn code:
public static function queryAddReturn($validation, $product_id, $way, $user_id, $count) {
    
  if( $validation !== true ) {
    return '<p class="text-light">Ошибка: товар уже заказан</p>';
  }
  else{
    if( Booking::addOne( $product_id, $way, $user_id, $count ) )
      return '<p class="text-light">Заказ успешно принят</p>';

    return '<p class="text-light">Ошибка: не удалось обработать заявку</p>';
  }
}

Moreover, in findByUserProduct var_dump($res) produces an array with the same $user_id and $product_id values ​​that were passed.
What could be the reason?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Troodi Larson, 2018-03-03
@troodi

Well, if you want everything to be in order, then use transactions. I didn't look at your code. but the essence of transactions is this: it blocks other operations until the request is completed.

D
Diman Suvorkin, 2018-03-04
@diman2000linda

It turned out. everything was due to the fact that on the client side the code was called twice. More precisely, on one button, two identical handlers were assigned per click. Ajax request went twice.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question