我正在尝试从行['得分']添加值。
例如,如果我有6行,每行的值为1 ..我希望能够回显 - >行数= 6。
+=
对我不起作用:我仍然只获取值本身,例如1,2,3,4,5,6,7但我想要它的总和,假设1 + 2 + 3 + 4 + 5 + 6 + 7 = 28。
由于
<?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>
答案 0 :(得分:1)
$sum=0;
while($row=mysql_fetch_array($result)){
$id = $row['id'];
$score = $row['score'];
if ($score == "1"){
$sum = $sum+$score;
}
}
echo $sum;
试试这个。 它取得了分数值。
答案 1 :(得分:0)
您必须删除if
条件并将数据库值添加到$sum
变量
$sum = 0;
while($row=mysql_fetch_array($result)){
$id = $row['id'];
$score = $row['score'];
$sum += (int)$score;
}
echo $sum;
答案 2 :(得分:0)
这里有几个问题,因为其他答案主要是修复,但要说清楚:
if $score == 1
似乎与您的目的无关。您的意思是if $id == 1
,还是只是想忽略零? (无论如何,任何+零都保持不变,所以你不需要)$sum += $score-1
echo
一次。目前,每个数据库行都有一个echo
,这就是您看到多个数字输出的原因。SELECT SUM(score) AS total_score FROM test
或SELECT id, SUM(score) AS total_score FROM test GROUP BY id