0

I have the following code

if(isset($_POST['submit']) || isset($_POST['mon']) || isset($_POST['yer']) || 
    isset($_POST['acty'])) {
        $mon = $_POST['mon'];
        $yer = $_POST['yer'];
        $acty = $_POST['acty'];
}

$str = "SELECT pty, SUM(`PW`) as Total 
        FROM heal 
        WHERE mon='$mon' 
          AND yer='$yer'  
        GROUP BY pty";

how can i pass the variable $acty into this: SUM('PW')....That is SUM('$acty')

Qirel
  • 25,449
  • 7
  • 45
  • 62
  • 2
    The `SUM()` is an SQL function. It will sum over the columns that is its argument. If your `$acty` is the name of a column, then `SUM($acty)` should suffice - but note that **your code is extremely insecure!!** Use a prepared statement instead. – Qirel Mar 04 '19 at 12:37

1 Answers1

0

exactly as you said.

$str = "
    SELECT 
        pty, 
        SUM($acty) as Total 
    FROM 
        heal 
    WHERE 
        mon='$mon' AND 
        yer='$yer'  
    GROUP BY 
        pty";

You can have variables inside double quotes and php will give you its contents.

Side Note: Your code is open for SQL Injection, you must need to prevent your code with SQL injection. Some useful links:

How can I prevent SQL injection in PHP?

Are PDO prepared statements sufficient to prevent SQL injection?

devpro
  • 16,184
  • 3
  • 27
  • 38
Vidal
  • 2,605
  • 2
  • 16
  • 32
  • note that this is **very unsafe code** Use a prepared statement instead. – Raymond Nijland Mar 04 '19 at 12:40
  • that's correct you should migrate your code to use PDO . http://php.net/manual/en/pdo.prepare.php – Vidal Mar 04 '19 at 12:44
  • I`m not sure you can bind column or table names in PDO. Probably you have to take that value and compare it with an array of columns. – Mihai Mar 04 '19 at 12:46
  • @Mihai you can work around it when you query `information_schema.COLUMNS` with a prepared statement and use that query result in a dynamic query.. This is safe because the .`information_schema.COLUMNS` View contains safe data.. The question is if you would allow users to control the column selection or not so you could add a whitelist to the query which columns are allowed to be selected. – Raymond Nijland Mar 04 '19 at 12:51
  • @Mihai also a other appraoch would be setting a user variable (SET variable := '') and use MySQL PREPARE/EXECUTE USING uservariable that is also safe against SQL injections. – Raymond Nijland Mar 04 '19 at 12:57
  • Thanks everyone for your contribution. i will look into the SQL Injection definitely. @Vidal i ran the query exactly the way you did yours even before asking this question but i get this error:................................. "Error code (1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') as Total FROM heal WHERE mon='' AND yer='' GROUP BY pty' at line 1" – Alfred Joseph Mar 04 '19 at 14:08