Reputation: 31
I know how to connect, display, remove, add data from my database and display all of it on my website. Everthing works correctly. I see my results on my website and in my database. I do this with AngularJS, AJAX and PHP but my problem is I don't know how to dispaly MYSQL SUM() one of my column. For example this is my table in mysql and I would like to dispaly the total sum of the money column.
id money
1 23
2 345
3 111
This is what I got:
index.html:
..................
<table class="table table-striped">
<tr>
<th>Money</th>
</tr>
<tr>
<td>{{ wcdrates.sumMoney }}</td>
</tr>
</table>
.................
I don't know If I should leave ng-repeat as it is or use something different instead. Anyway ng-repeat dosent'work. It shows me all results from money column not the total SUM. ............
controller.js
.....................
$http.post('./php/showMoney.php')
.success(function(data) {
$scope.wcdrates = data;
})
.error(function(err) {
$log.error(err);
})
....................
connectDatabase.php
<?php
define("__HOST__", "127.0.0.1");
define("__USER__", "root");
define("__PASS__", "");
define("__BASE__", "davbaza");
class DB {
private $con = false;
private $data = array();
public function __construct() {
$this->con = new mysqli(__HOST__, __USER__, __PASS__, __BASE__);
if(mysqli_connect_error()) {
die("DB connection failed:" . mysqli_connect_error());
}
}
public function qryPop() {
$sql = "SELECT * FROM `wcdrates` ORDER BY `id` DESC";
$qry = $this->con->query($sql);
if($qry->num_rows > 0) {
while($row = $qry->fetch_object()) {
$this->data[] = $row;
}
} else {
$this->data[] = null;
}
$this->con->close();
}
public function qryFire($sql=null) {
if($sql == null) {
$this->qryPop();
} else {
$this->con->query($sql);
$this->qryPop();
}
//$this->con->close();
return $this->data;
}
}
?>
showMoney.php
<?php
include('connectDatabase.php');
$db = new DB();
$sql = "SELECT SUM(money) as sumMoney FROM wcdrates";
$data = $db->qryFire();
echo json_encode($data);
mysql
CREATE TABLE IF NOT EXISTS `wcdrates` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`money` int(11) NOT NULL,
PRIMARY KEY (`id`)
)
I have no idea what I should change to get what I want.
Upvotes: 1
Views: 351
Reputation: 777
change the qryPop
in your code , to following code .
$sql = "SELECT id,money , SUM(money) as sumMoney FROM `wcdrates` ORDER BY `id` DESC";
Hope you will get the answer
Upvotes: 2