0

thank you before for take an interest into my case. In short i want to tell that i wonder if Value in MySQL table can be counted using by just MySQL query or need PHP code to count. And i have no idea how to code it.

Case :

I have tbl_transaction which has format like this :

id | ref | description | value | date | category | sub_category

Value is an INT type column, for example it contains 10000, 20000, etc..

Let's say that i want to SUM value column, but by DISTINCT Category

So for example, it's going to work like this :

category A SUM minus(-) category B SUM plus(+) category C SUM = Result of Counted SUM

Experiment :

I tried something like this, obviously wont work but i try to show my logic for solve a case here.

SELECT SUM(value) as MAIN_CAT_TOTAL_VAL 
  FROM tbl_transaction 
 WHERE monthTransaction LIKE '$newmonthminusone%' ONE
     , ONE+3

Desired Learning :

I want to know how mySQL query can be printed into PHP. And code behind that if possible, i actually need the code. Some say that mysql_ function isnt really up-to-date anymore and shouldn't be used. But i have no bright knowledge on how to use new function that replace mysql_ function, like maybe PDO and some kind like that. I really need explanation. I learn from code and case, that's how i adapt at least. So code would be help me much.

Desired Output :

Number / value, result of SUMMED UP table calculation (math). 

I have no idea at all, how to code and start. Been stuck for hours. I sincerely need help for this. Ty so much.

  • Your table structure doesn't seem to have a 'monthTransaction' column, but your sample query does. The query you're looking for is `SELECT category, SUM(value) AS categoryTotal FROM tbl_transaction GROUP BY category;`. If you're familiar with the deprecated `mysql_` functions, try using the `msqli_` equivalents – charmeleon Jul 28 '16 at 15:20
  • If you can't do this with MySQL, it would be easy using a while loop in PHP, but I think someone will have a MySQL answer – The One and Only ChemistryBlob Jul 28 '16 at 15:21
  • i assume the result is true, but i still need to print out that to php, do you have any idea with that ? (php). this mysql query maybe true, based on my logic to read this query. – Keshia Angelina Jul 28 '16 at 15:25
  • @TheOneandOnlyChemistryBlob actually i prefer both mySQL and PHP query, since it need to be printed out in PHP – Keshia Angelina Jul 28 '16 at 15:26
  • 2
    Possible duplicate of [PHP & MySQL : Show SUM of Something, Classified By Distinct Category](http://stackoverflow.com/questions/38620282/php-mysql-show-sum-of-something-classified-by-distinct-category) – Guilherme Vaz Jul 28 '16 at 15:45
  • @GuilhermeVaz it's my question and i can assure you that is different, totally. i want to do sum of value math calculation here, which isnt there, thats why im asking on different question. i wont ask same question twice, especially when its my own question. – Keshia Angelina Jul 28 '16 at 15:56

3 Answers3

2

To sum the values from one category

SELECT category, SUM(value) FROM tbl_transaction GROUP BY category

I hope you have enough knowledge to expand this query to include more fields or filter out, what you don't want included in the sum.

Jakumi
  • 8,043
  • 2
  • 15
  • 32
2

mysqli_* is pretty much a drop-in replacement for mysql_*, and is a good transition to learning PDO, as you can use your (mostly) unmodified existing code, and transition toward the object-oriented approach and prepared statements as you learn about them.

That said, what you are probably looking for in a query is something like:

SELECT
    category,
    SUM(value) AS MAIN_CAT_TOTAL_VAL
FROM tbl_transaction
WHERE monthTransaction LIKE '$newmonthminusone%' AS ONE
GROUP BY category;

Then you'll be able to work with it like so:

$link = mysqli_connect("localhost", "dbuser", "dbpassword", "dbname");
$query = mysqli_query($link, $queryStringFromAbove);
$total = 0;
while($row = mysqli_fetch_assoc($query)) {
    switch($row['category']) {
        case "A":
        case "C":
            $total += $row['MAIN_CAT_TOTAL_VAL'];
            break;
        case "B":
            $total -= $row['MAIN_CAT_TOTAL_VAL'];
            break;
    }
}
echo $total;

Edit: It's difficult to tell precisely your conditions of adding or subtracting, but the switch() block should be flexible enough to customize to your needs.

Jerbot
  • 1,168
  • 7
  • 18
  • i actually tried this, but actually i want to do math (calculation) for summed up value. the example is : the SUM of A table is 1000, the SUM of B table is 2000. Then i want to calculate both of SUM, resulted in -1000. that's what im seeking, i try for hours and still cant figure it out. and thank you for your answer. – Keshia Angelina Jul 28 '16 at 15:39
  • So I'm assuming `category` is storing this A, B, and C table designation? And your math will always be A - B + C? – Jerbot Jul 28 '16 at 15:44
  • yes yes, just like that. btw math isnt always A - B + C. actually i want sum of distinct category and then count them like A - B + C. i currently making function for count total of last month transaction and total of current month transaction, something like that – Keshia Angelina Jul 28 '16 at 15:51
  • thank you for the last edit, i currently try to implement the code. but it's return to 0 value. but thank you anyway, i really appreciate your help. – Keshia Angelina Jul 28 '16 at 16:25
  • You'll have to make sure the `case ""` matches exactly the values in your `category` column. Without seeing a snippet of the table, I had to guess. – Jerbot Jul 28 '16 at 16:28
  • i tried to enter $queryStringFromAbove with correct (working) query, its really working in mysql (the query). i also tried to change case to double + and double - just in case the value is actually zero, but still the value is zero. i still figure this out, the query is true, but i think something in a switch-case.. – Keshia Angelina Jul 28 '16 at 16:39
  • update : i tried to add default value to switch case and it actually work, i just have to make indexed value use some case. its like an if. thank you, i hope i will figure it out soon. – Keshia Angelina Jul 28 '16 at 16:58
  • update : wow, it works amazingly ! thank you!! i was not pay attention to switch case code.. thank you very much, really work ! – Keshia Angelina Jul 28 '16 at 17:03
  • Glad we were able to get it figured out. Have fun learning database application development! – Jerbot Jul 28 '16 at 17:07
1

@SuperJer has the solution for mysqli. If you want the mysql solution:

// Create connection to your server
$handle=mysql_connect('your_server_name','your_server_password');

// Check that connection was successful
if($handle == FALSE)
   die("No connection available: ".mysql_error());

// Select your database
$db=mysql_select_db('your_database_name');
if($db == FALSE)
   die("Unable to select DB: ".mysql_error());

// Formulate query
$query = SELECT category, SUM(value) AS categoryTotal FROM tbl_transaction GROUP BY category;

// Run query
$result = mysql_query($query, $handle);

// Store result
$total = 0;    
while($row=mysql_fetch_assoc($result)){
    switch($row['category']) {
    case "A":
    case "C":
        $total += $row['MAIN_CAT_TOTAL_VAL'];
        break;
    case "B":
        $total -= $row['MAIN_CAT_TOTAL_VAL'];
        break;
    }
}

I hope this helps

pjcognetta
  • 83
  • 7
  • i actually still figure this out along with @SuperJer code, thank you so much, so far i try, this code return to 0 value. but i gonna figure it out, thank you, its helping – Keshia Angelina Jul 28 '16 at 16:24