id = primary and auto increment
users = varchar
votes = int
如何汇总投票字段内的值并回显呢?
答案 0 :(得分:4)
试试这个,
$result = mysql_query('SELECT SUM(votes) AS value_sum FROM table_name');
$row = mysql_fetch_assoc($result);
$sum = $row['value_sum'];
使用SQLi
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT SUM(votes) AS value_sum FROM table_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "sum is : " . $row["value_sum"];
}
} else {
echo "0 results";
}
$conn->close();
答案 1 :(得分:1)
1)查询:
SELECT SUM(votes) FROM `table`
2)将结果放入变量并回显它。