2013-05-28 67 views
0

我有一個SQL查詢,我想選擇兩個日期之間支付的記錄。PHP SQL concatenation

以下是我建我的查詢:

$qry = array(); 
    $qry[] = "SELECT DISTINCT 2 AS Record_Type, wp_woocommerce_order_items.order_id As Order_Id, First_Name; 
    $qry[] = "FROM wp_woocommerce_order_items"; 
    $qry[] = "LEFT JOIN (SELECT meta_value As First_Name, post_id FROM wp_postmeta WHERE meta_key = '_shipping_first_name') AS a"; 
    $qry[] = "ON wp_woocommerce_order_items.order_id = a.post_id"; 
    $qry[] = "RIGHT JOIN (SELECT post_id FROM wp_postmeta WHERE meta_key = '_paid_date' AND meta_value > " .$_POST['debut'] . " AND meta_value < " . $_POST['fin'] . ") AS m"; 
    $qry[] = "ON wp_woocommerce_order_items.order_id = m.post_id"; 
    $qry[] = "WHERE wp_woocommerce_order_items.order_item_type = 'line_item'"; 
    $qry[] = "ORDER BY wp_woocommerce_order_items.order_id"; 

的問題是在正確的我POST變量聯接線。如果我硬編碼日期而不是$ _POST ['debut']和$ _POST ['fin'],我會得到我期待的結果。

所以我想我的問題是從我的PHP POST變量連接。

任何人都可以幫到我嗎?

+1

你是認真暴露你的後端向被攻擊者受到損害顯著風險,如果您嵌入用戶變量直接進入您的SQL查詢。 –

+1

您錯過了陣列中第一個元素末尾的雙引號 –

回答

3

您需要引用您的值,例如的

$qry[] = "RIGHT JOIN (SELECT post_id FROM wp_postmeta WHERE meta_key = '_paid_date' AND meta_value > " .$_POST['debut'] . " AND meta_value < " . $_POST['fin'] . ") AS m"; 

使用

$qry[] = "RIGHT JOIN (SELECT post_id FROM wp_postmeta WHERE meta_key = '_paid_date' AND meta_value > '" .$_POST['debut'] . "' AND meta_value < '" . $_POST['fin'] . "') AS m"; 

來代替,請認準mysql_real_escape_string或其他方式,以避免SQL注入攻擊。

+0

好的謝謝!我也要看看SQL注入。 – CharleyXIV

1

使用此

$qry[] = "SELECT DISTINCT 2 AS Record_Type, wp_woocommerce_order_items.order_id As Order_Id, First_Name 
    FROM wp_woocommerce_order_items 
    LEFT JOIN (SELECT meta_value As First_Name, post_id FROM wp_postmeta WHERE meta_key = '_shipping_first_name') AS a 
    ON wp_woocommerce_order_items.order_id = a.post_id 
    RIGHT JOIN (SELECT post_id FROM wp_postmeta WHERE meta_key = '_paid_date' AND meta_value > '" .$_POST['debut'] . "' AND meta_value < '" . $_POST['fin'] . "'') AS m 
    ON wp_woocommerce_order_items.order_id = m.post_id 
    WHERE wp_woocommerce_order_items.order_item_type = 'line_item' 
    ORDER BY wp_woocommerce_order_items.order_id";