Kavya Shree Kavya Shree - 23 days ago 7
MySQL Question

How to add PHP variable value to Between Query

Below is my query

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;

}


How Can I add tht passed from1 and to1 value into Between from date and to date.If I apply variable direclty or with single quite Its showing error.Kindly help me anyone.

Answer

As you are using PDO you should also be using Parameterized queries like this

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

This also removes all the issues of how to concatenate data into your query, as it is all looked after by PDO, and also removes any SQL Injection issues with data received from the user