1

From Android I post name="organisation", value="wwf". In the $sql variable $organisation works but when using same variable in the echo it doesn't.

If $organisation is replaced with wwf in the echo works as inteded and returns the amount of users who selected wwf in the database.

Moving around " .$organistion. but only get the correct result when hardcode wwf in the sum.

$organisation = $_POST["organisation"];

$sql = "select sum(`$organisation`) from `users` where `$organisation`=1";
$result = mysqli_query($conn,$sql) or die ("Bad Query: $sql");

while ($count = mysqli_fetch_assoc($result)){
    //print_r($count);
    echo"{$count['sum(`$organisation`)']}"; 
}

Var $organisation in my sql query works as intended but in the echo it doesn't return a value. The var $organisation doesn't seem to have the right format to return its value when used in sum from the array print_r produces.

Erik Dreifaldt
  • 773
  • 7
  • 13
  • 1
    This SQL statement could lead to a SQL Injection, you may want to look into [prepared statements](https://www.w3schools.com/php/php_mysql_prepared_statements.asp) to prevent that. – Gert de Pagter Jun 11 '19 at 13:45

1 Answers1

2

Give the column in your SQL an alias so you can get it back out easier:

$sql = "select sum(`$organisation`) AS org_count from `users` where `$organisation`=1";

Then you can use

echo $count['org_count'];

to get the value back out.

By the way, you really shouldn't blindly allow $organisation from a post value. Check it against existing columns first, or else someone can easily break your query.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
aynber
  • 22,380
  • 8
  • 50
  • 63