Reputation: 71
I'm trying to add values from row['scores'].
For example, if I have 6 rows that have a value of 1 for each row .. I want to be able to echo -> value of rows = 6.
The +=
is not working for me: I still get only the values themselves, e.g. 1,2,3,4,5,6,7 but I want the sum of it, let's say 1+2+3+4+5+6+7=28.
Thanks
<?php include("connect.php"); ?>
<html>
<head>
<title>Score Predictions</title>
</head>
<body>
<div id = "id">
<?php
$query = "SELECT * FROM test";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
}
?>
<?php
if (isset($_POST['submit'])) {
$x = $_POST["test"];
mysql_query("INSERT INTO test (home, away, score) VALUES ('$home', '$away', '$x')");
}
?>
<?php echo $home," - ",$away; ?>
<form method = 'post' action = 'http://albsocial.us/test/index.php'>
<select name = 'test'>
<option value = "" selected = 'selected'></option>
<option VALUE = '1'>1</option>
<option VALUE = 'X'>X</option>
<option VALUE = '2'>2</option>
</select>
<INPUT TYPE = 'submit' name = 'submit' />
</form>
<?php
$query = "SELECT * FROM test";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$score = $row['score'];
if ($score == "1") {
echo $sum += $score - 1;
}
}
?>
</div>
</body>
</html>
Upvotes: 0
Views: 9936
Reputation: 97718
Several problems here, as other answers mostly fix, but to make clear:
if $score == 1
doesn't seem relevant to your purpose. Did you mean if $id == 1
, or were you just trying to ignore zeros? (anything + zero stays the same anyway, so you don't need to)$sum += $score-1
either echo
once. Currently, you have an echo
for every database row, which is why you're seeing multiple numbers output.SELECT SUM(score) AS total_score FROM test
or SELECT id, SUM(score) AS total_score FROM test GROUP BY id
Upvotes: 0
Reputation: 30488
You have to remove the if
condition and add the database value to $sum
variable
$sum = 0;
while($row=mysql_fetch_array($result)){
$id = $row['id'];
$score = $row['score'];
$sum += (int)$score;
}
echo $sum;
Upvotes: 2
Reputation: 1756
$sum=0;
while($row=mysql_fetch_array($result)){
$id = $row['id'];
$score = $row['score'];
if ($score == "1"){
$sum = $sum+$score;
}
}
echo $sum;
try this. it sume al $score values.
Upvotes: 2