fry2010 Posted March 4, 2009 Share Posted March 4, 2009 Ok thanks to samshel for how to find last week start, I have been entering information into database. The problem I am having now is running a loop to get the values of each column in the database and adding them together. Lets say that yesterday I have 4 columns. The first column has a value of 10, the next has 20 the next has 30 and the last column has a value of 40. I am selecting this info with the following sql statment: $conn = db_connect(); $result = $conn->query("SELECT int FROM history WHERE date = DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND porl = 'true'"); $column = $result->fetchColumn(); Now I need to use a loop to go through each column and add the values together to get 100. (10 + 20 + 30 + 40 = 100). I have tried using a for loop as such: $row = $result->fetchObject(); for($i=; $i<$column; $i++ ) { $value += $row->int; } But this returns 180. Link to comment https://forums.phpfreaks.com/topic/147928-solved-issue-with-loop/ Share on other sites More sharing options...
rhodesa Posted March 4, 2009 Share Posted March 4, 2009 #1) INT is a reserved word. You should NOT use it as a column name. Are they columns or rows? Either way, it is probably better to SUM them in your SQL statement. Link to comment https://forums.phpfreaks.com/topic/147928-solved-issue-with-loop/#findComment-776381 Share on other sites More sharing options...
fry2010 Posted March 4, 2009 Author Share Posted March 4, 2009 oh yeah im not actually using INT in the code I just put it there to help understand the value Im after is an integer. I believe I am after rows, yeah so I shouldnt be using column. SUM sounds like a better idea, I will go look it up, thanks a lot rhodesa. Ill see what I can find... Link to comment https://forums.phpfreaks.com/topic/147928-solved-issue-with-loop/#findComment-776388 Share on other sites More sharing options...
rhodesa Posted March 4, 2009 Share Posted March 4, 2009 try something like this: $conn = db_connect(); $result = $conn->query("SELECT SUM(columnName) as columnSum FROM history WHERE date = DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND porl = 'true'"); $row = $result->fetchRow(); print $row->columnSum; Link to comment https://forums.phpfreaks.com/topic/147928-solved-issue-with-loop/#findComment-776399 Share on other sites More sharing options...
fry2010 Posted March 4, 2009 Author Share Posted March 4, 2009 Yeah that is roughly what I had done, I just needed that part where you change the SUM(columnName) as columnSum, to get it to return value. I am using PDO so I cant use fetchRow. Working perfectly now. Awesome Thanks for all your help. Link to comment https://forums.phpfreaks.com/topic/147928-solved-issue-with-loop/#findComment-776416 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.