我做了一些关于如何总结MySQL中列的值的研究,发现SELECT SUM
是最好的方法,但我花了好几个小时尝试解决这个问题,我仍然可以'让它工作:
以下是代码:
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query('SELECT SUM(price) AS value_sum FROM xCarts_'. $useXsesh .'_sandwiches');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
echo $sum;
mysqli_close($conn);
这是表格:
答案 0 :(得分:2)
您正在使用OOP样式连接到数据库,然后尝试使用过程样式来获取数据
您需要将程序转换为OOP;
这一行:
$result = mysqli_query('SELECT SUM(price) AS value_sum FROM xCarts_'. $useXsesh .'_sandwiches');
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
应如下:
$result = $conn->query('SELECT SUM(price) AS value_sum FROM xCarts_'. $useXsesh .'_sandwiches');
$row = $result->fetch_assoc();
$sum = $row['value_sum'];
如果你需要保持程序风格,请使用程序样式连接到mysqli:
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
然后将您的连接传递给mysqli_ *函数,如下所示:
$result = mysqli_query($conn, 'SELECT SUM(price) AS value_sum FROM xCarts_'. $useXsesh .'_sandwiches');
// ^^^^^
$row = mysqli_fetch_assoc($result);
$sum = $row['value_sum'];
答案 1 :(得分:0)
您的查询很好。也许你的' id'属性不是数字类型?