D
D
Denis2021-02-11 13:43:21
PHP
Denis, 2021-02-11 13:43:21

Why is the WHERE condition not met?

if ($promo == 'NEWUSER'){
  if($bd->Query("SELECT COUNT(*) FROM users_nykfageubf WHERE p = '$p' AND promo_new=1")){
    $bd->Query("UPDATE users_nykfageubf SET promo_new = 0 WHERE p = '$p'");
    $bd->Query("UPDATE users_nykfageubf SET balance=balance+10 WHERE p = '$p");
  } else {
    echo '<div class="alert-msg"><a href="#" class="close-alert"><i class="fa fa-times"></i></a><p>Вы уже использовали промокод.</p></div>';
       }
}


There is such a code snippet. Implemented the use of a promotional code. By design, the user $p is checked to see if he used the promo_new promo code (1 - no, 0 - yes). If not, then the balance is increased by 10 and promo_new = 0; The only problem is that no matter what value is in promo_new, the user can use the promo code an unlimited number of times and get +10 on the balance. I don’t understand why, because WHERE is present and everything is clearly indicated.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Slava Rozhnev, 2021-02-11
@rozhnev

because


$bd->Query("SELECT COUNT(*) FROM users_nykfageubf WHERE p = '$p' AND promo_new=1"))

always returns true - the query was successful, not the number of rows found
By the way, two queries should be combined into one:
$bd->Query("UPDATE users_nykfageubf SET balance=balance+10, promo_new = 0 WHERE p = '$p' AND promo_new=1");

and as a test, use a faster query:
$stmt = $bd->Query("SELECT 1 FROM users_nykfageubf WHERE p = '$p' AND promo_new=1 LIMIT 1");
if ($stmt->rowCount() > 0) {
    ...........
}

R
Rsa97, 2021-02-11
@Rsa97

On a good note, all three queries should be combined into one, rewritten with placeholders and check mysqli::$affected_rows or PDOStatement::rowCount after the query. This way you can avoid the race condition.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question