2016-11-15 38 views
0

下面是我的查詢如何PHP變量值添加到查詢之間

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; 

} 

我如何添加THT順利通過1跳轉和TO1從日期和date.If重視,往來成我申請的變量照片直接或單一相當它顯示錯誤。善良幫助我的人。

+0

您正在使用'prepare',但沒有真正使用它。閱讀[文檔](http://php.net/manual/en/pdo.prepare.php)。有很多如何正確執行此操作的示例,這些示例還將解決您的問題。 –

+0

你使用PDO或mysqli_數據庫訪問API嗎? – RiggsFolly

+0

我使用PDO數據庫訪問 –

回答

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注入問題

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; 

    } 
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查詢。