PHP - Add everything and give a value

1

Good,

I created this script to check the DB, add all the records with that ID and then give an alert with the total sum.

But ... it's not giving, just show 1 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 is not adding all this client_id ????

    
asked by anonymous 17.06.2018 / 00:27

2 answers

3

You have to give your alert after 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>"; 
    
17.06.2018 / 01:29
1

I believe you are using PDOs in the query.

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

On your question, I would do the sum natively with SQL itself and not with PHP because I did not see the need to do that for the script you showed.

Here is an example I made with a database 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>
    
17.06.2018 / 14:12