I want to sum some columns together based on a array. Previous I did it like this:
$data = $db->query("SELECT idnummer, productnaam,($kolommen[0]+$kolommen[1]+$kolommen[2]+$kolommen[3]+$kolommen[4]+$kolommen[5]+$kolommen[6]+$k
olommen[7]+$kolommen[8]+$kolommen[9]+$kolommen[10]+$kolommen[11]+$kolommen[12]+$kolommen[13]+$
kolommen[14]) AS total FROM wasmachine ORDER BY total DESC, prijs LIMIT 0, 5") or
trigger_error("Fout in de query");
But I think this is not the right way to do it, because I want it dynamically. I want to use the full array like
$data = $db->query("SELECT idnummer, productnaam,($kolommen) AS total FROM wasmachine ORDER BY total DESC, prijs LIMIT 0, 5") or
trigger_error("Fout in de query");
This is my database example:
idnummer | productnaam | v1a2 | v2a1 | v3a2
1 | test 1 | 1 | 2 | 1
2 | test 2 | 1 | 2 | 1
3 | test 3 | 1 | 2 | 1
4 | test 4 | 1 | 2 | 1
I tried it with array_sum and count but I can't figure it out.
Thanks for helping me!
As I understand, your $kolommen array contains names of all rows you need to sum? Then you can write your query this way:
"SELECT idnummer, productnaam,(".join('+', $kolommen).") AS total FROM wasmachine ORDER BY total DESC, prijs LIMIT 0, 5"
Function join will glue elements of the array with string '+'.
Your can use implode as alias function of join, if you wish.