2016-05-17 148 views
1

我正在轉換網站上的舊式MySQL/PHP查詢。我有一個包含一系列複選框的頁面。這被提交,查詢是基於檢查哪些複選框建(至少有6樣以下):動態構建PHP PDO MySQL查詢

if (xxxxx) { 
    $furthersort=$furthersort."AND age_birth='yes' "; 
    } 
if (xxxxx) { 
    $furthersort=$furthersort."AND age_three='yes' "; 
    } 

... 

$prequery = "SELECT id from products WHERE product_categories LIKE '%$catid%' ".$furthersort."ORDER BY product_name ASC"; 

我想這在移動第二部分PHP這樣的:

$query = $objDb->prepare("SELECT id from products WHERE product_categories LIKE ? ? ORDER BY product_name ASC"); 
$params3 = array('%$catid%',$furthersort); 
$query->execute($params3); 
while ($row = $query->fetch(PDO::FETCH_ASSOC)); 

但它不工作。由if創建的變量是正確的,所以我確定這是因爲我錯過了對準備部分如何解釋信息的理解,但我需要朝正確的方向推動。

+0

'$ furthersort'是什麼,或者你想要綁定的第二件事是什麼? – chris85

+1

當你不應該有一樣東西時,你在'LIKE'中有兩件事。你可以連接你的數組,但不確定你連接到LIKE定界符的外部。 –

+0

@JayBlanchard ***作爲一個主人當然有它的地方......; - )***像水晶般清澈......但是,並非所有的主人都盡力做到最好...... *** * *對於像你這樣的老師,牆上的字跡很清楚,但是新出生的只有1個SO聲望??? ** – Poiz

回答

5

你有兩個問題。首先,你只能爲LIKE條件一個綁定參數,所以你必須聲明,以及隨後的條件:

$query = $objDb->prepare("SELECT id from products WHERE product_categories LIKE ? AND age_three = ? ORDER BY product_name ASC"); 

現在你可以在陣列中發送兩個值現在

$furthersort = 'yes'; 
$params3 = array("%$catid%", $furthersort); 

,給予我們不知道如何設置$furthersort很難提供準確的東西供您使用,但對於您添加到查詢中的每種情況而言,只要說明一下,就必須添加另一個綁定參數,如果您打算繼續沿着創建動態查詢的行。這樣做的邏輯比我在這裏展示的要複雜得多。

+0

有!就在那裏........ **大起來!!! – Poiz

0

像Blanchard先生指出的那樣,您似乎無意中在您的LIKE子句中添加了2個佔位符,而不是1個佔位符。它應該是:

  <?php 
      // RIGHT AFTER THE LIKE YOU HAD 2 PLACE-HOLDERS: ? ? RATHER THAN JUST 1: ? 
      if (xxxxx) { 
       // YOU ARE CONCATENATING "AND" DIRECTLY TO THE $furthersort VARIABLE WITHOUT A SPACE: WRONG... 
       // $furthersort = $furthersort."AND age_birth='yes' "; 
       $furthersort = $furthersort." AND age_birth='yes' "; 
      } 
     if (xxxxx) { 
       // YOU ARE CONCATENATING "AND" DIRECTLY TO THE $furthersort VARIABLE AGAIN WITHOUT A SPACE: WRONG... 
       // $furthersort = $furthersort."AND age_three='yes' "; 
       $furthersort = $furthersort." AND age_three='yes' "; 
      } 

     ... 

     $prequery = "SELECT id from products WHERE product_categories LIKE '%"; 
     $prequery .= $catid . "%' " . $furthersort. " ORDER BY product_name ASC "; // <== WHITE SPACE IS GRATIS IN MYSQL 


     $sql  = "SELECT id from products WHERE product_categories LIKE :CAT_ID ORDER BY product_name ASC"; 
     $query  = $objDb->prepare($sql); 
     // $params3 = array('%$catid%', $furthersort);  <== VARIABLE INSIDE SINGLE QUOTES!!! YOU MAY USE DOUBLE QUOTES... 
     $params3 = array("CAT_ID"=>"%" . $catid . "%" . $furthersort); 
     $query->execute($params3); 
     while ($row = $query->fetch(PDO::FETCH_ASSOC));