PHP - Add everything and give a value

Asked

Viewed 211 times

1

Good,

I created this little script to check from DB, add all Cords with that ID and then give an Alert with the total sum.

But... it’s not on, it just shows a record.

 $exp_selector = "SELECT reward_qty FROM public_rewards WHERE client_id = '".$_SESSION['u_id']."'";     
 $exp_query = $con->query($exp_selector);

 $reward_exp = rand(10,25);        

  while($exp_detail = $exp_query->fetch_array()) {

        $percentages = $exp_detail['reward_qty'];
        $sum_value += $percentages;         

        echo "<script>alert('$sum_value');</script>"; 

  }

Why aren’t you adding up all of that client_id????

2 answers

3

You have to give your Alert after the while

$exp_selector = "SELECT reward_qty FROM public_rewards WHERE client_id = '".$_SESSION['u_id']."'";     
$exp_query = $con->query($exp_selector);

$reward_exp = rand(10,25);  

#antes do while, definir sum_value com valor 0
$sum_value = 0;

while($exp_detail = $exp_query->fetch_array()) {

      $percentages = $exp_detail['reward_qty'];

      #aqui atualizamos o valor de sum_value somando o valor antigo + o novo recebido do banco de dados
      $sum_value = $sum_value + $percentages;     
}

#depois o que o while terminar, passará ao alert mostrando o valor final da variável sum_alert
echo "<script>alert('$sum_value');</script>"; 

1

I believe you are using PDO in the query.

As you are passing a parameter in the query would recommend first that you always use PREPARE and not directly concatenate the variable in the query because it opens a security breach.

About your doubt, I would do the sum natively with SQL itself and not with PHP because I didn’t see the need to do it by the script you showed.

Here is an example I made with a base I tested here:

<?php

$idCli = 0;

$con = new PDO("mysql:host=127.0.0.1;dbname=teste", "root", "root");
$stmt = $con->prepare('select sum(valor) as total from conta where idCli = :idCli');
$stmt->bindParam(':idCli', $idCli);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);

/*
array(1) {
  ["total"]=>
  string(2) "20"
}
*/

?>

<script>alert(<?php echo $row['total'] ?>);</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.