Search code examples
phpvariablespostsumvar

Echo variable from $_POST["organisation"] only works in sql query and not in sum of result


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.


Solution

  • 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.