sql语句中的变量

时间:2019-03-04 12:31:43

标签: php mysql

我有以下代码

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";

如何将变量$acty传递给变量:SUM('PW') ....即SUM('$acty')

1 个答案:

答案 0 :(得分:0)

与您所说的完全一样。

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

您可以在双引号中包含变量,而php会为您提供其内容。

侧面说明:您的代码已打开以进行SQL注入,您必须防止使用SQL注入来防止代码。一些有用的链接:

How can I prevent SQL injection in PHP?

Are PDO prepared statements sufficient to prevent SQL injection?