如何将PHP变量值添加到Between Query之间

时间:2016-11-15 09:34:44

标签: php mysql

以下是我的查询

public function total_registration_month($from1,$to1){

    $q = $this->link->prepare('SELECT advisor, COUNT(*) as total
        FROM
        (
                SELECT advisor 
                FROM training_details 
                WHERE ndate BETWEEN $from1 AND $to1 
            UNION ALL
                SELECT advisor 
                FROM student_details 
                WHERE registereddate 
                BETWEEN $from1 AND $to1
        ) AS advisor
        GROUP BY advisor');

    $q->execute();

    $count = $q->fetchall();

    return $count;

} 

如何将from1和to1值从日期和日期之间添加到Between之间。如果我应用变量direclty或单个相当显示错误。请帮助我任何人。

3 个答案:

答案 0 :(得分:1)

当您使用PDO时,您还应该使用像这样的参数化查询

public function total_registration_month($from1,$to1){

    $q = $this->link->prepare('SELECT advisor, COUNT(*) as total
                                FROM
                                (
                                        SELECT advisor 
                                        FROM training_details 
                                        WHERE ndate BETWEEN :fromd AND :tod 
                                    UNION ALL
                                        SELECT advisor 
                                        FROM student_details 
                                        WHERE registereddate BETWEEN :fromd1 AND :tod1
                                ) AS advisor
                                GROUP BY advisor');

    $params = array(':fromd' => $from1,':tod' => $to1,
                    ':fromd1' => $from1,':tod1' => $to1);

    $res = $q->execute($params);
    if ( ! $res ) {
        print_r( $q->errorInfo() );
        exit;
    }

    $count = $q->fetchall();
    return $count;
} 

这也消除了如何将数据连接到查询中的所有问题,因为它全部由PDO负责,并且还消除了从用户收到的数据的任何SQL注入问题

答案 1 :(得分:0)

public function total_registration_month($from1,$to1){

        $q = $this->link->prepare("SELECT advisor, COUNT(*) as total
        FROM
        (
                SELECT advisor 
                FROM training_details 
                WHERE ndate BETWEEN '$from1' AND '$to1' 
            UNION ALL
                SELECT advisor 
                FROM student_details 
                WHERE registereddate 
                BETWEEN '$from1' AND '$to1'
        ) AS advisor
        GROUP BY advisor");
        $q->execute();

        $count = $q->fetchall();

        return $count;

    } 

答案 2 :(得分:0)

使用PDO连接时,请尝试以下代码:

$q = $this->link->prepare('SELECT advisor, COUNT(*) as total
    FROM
    (
            SELECT advisor 
            FROM training_details 
            WHERE ndate BETWEEN ? AND ? 
        UNION ALL
            SELECT advisor 
            FROM student_details 
            WHERE registereddate 
            BETWEEN ? AND ?
    ) AS advisor
    GROUP BY advisor');

$q->execute(array($from1,$to1,$from1,$to1));

$count = $q->fetchall();

注意'?' (问号)在sql查询中。