2014-02-14 45 views
0

我想寫一些PHP代碼,將查詢數據庫表的最後10行(由三個字段組成),並搜索字符串/子字符串的任何實例「單詞」並對它們進行計數 - 包括單個單元格中的多次。以下是我迄今爲止:使用PHP查詢子表的字段

$query = "SELECT * from my_table WHERE column1 LIKE '%word%' 
       UNION ALL SELECT * from my_table WHERE column2 LIKE '%word%'"; 

    $result = mysqli_query($mysqli, $query); 

    $i = 0; 
    while($row = mysqli_fetch_array($result)) 
    { 
     $i++; 
    } 
    echo "<i>This table contains [" . $i . "] instances of the string \"word\".</i>"; 

    mysqli_free_result($result); 
    mysqli_close($mysqli); 

我遇到的問題是:

  1. 這是我的輪詢整個數據庫,而不只是最後10行。如果我包含「ORDER BY PID DESC LIMIT 10」,查詢不再適用於WHERE和LIKE。

  2. 它不捕獲單個單元格中字符串的多個實例。

我花了幾個小時在這 - 我會很感激任何意見。非常感謝!

/** ** UDPATE/

這裏是我結束了。本質上,我將我的查詢轉換爲一個數組,然後轉換爲一個字符串。從那裏我搜索了「單詞」的所有實例。感謝大家的幫助。

$query = "SELECT * FROM my_table ORDER BY PID DESC LIMIT 10"; 
    $result = mysqli_query($mysqli, $query); 

    $j = 0; 
    $i = 'word'; 

    while ($row = mysqli_fetch_array($result)) 
    { 
    $intoarray = implode(",", $row); 
    $j += substr_count($intoarray, $i); 
    } 

    echo "<i>This table contains [" . ($j/2) . "] instances of the string \"word\".</i>"; 

回答

0

嘗試對錶和列的所有名稱使用反引號。您可以在美式鍵盤上找到`,就在您的<TAB>鍵的正上方。例如:

原來的答案:

"SELECT * from `my_table` WHERE `column1` LIKE '%word%'" 

市價修改意見如下:

$query = "SELECT * from `my_table` WHERE `column1` LIKE '%word%' 
      UNION ALL SELECT * from `my_table` WHERE `column2` LIKE '%word%'"; 

此查詢運行我的服務器上的罰款。

+0

和工作一個友好的提示 - 儘量避免mysql被淘汰,並將被折舊 - 使用PDO。它會讓你免於麻煩。 – Faron

+0

添加了它們。結果似乎沒有任何區別。我試圖添加聲明ORDER BY PID DESC LIMIT 10後添加它們,沒有任何改變。 #fustrated! – nickm

+0

什麼是您在SQL中定義的PID?也許這樣做:'SELECT * FROM \'members \'WHERE \'column1 \'LIKE'%word%'ORDER BY'PID \'DESC LIMIT 10' – Faron

0

我創建以下查詢我的表,它工作正常

(select * from eas_appliciant 
where appliciant_id = '6' 
order by appliciant_id limit 0,1) 
union all 
(select * from eas_appliciant 
where appliciant_id = '7' 
order by appliciant_id limit 0,1) 

您可以創建也跟着

( SELECT column1 as selected_column from my_table 
    WHERE column1 LIKE '%word%' 
    ORDER BY PID DESC LIMIT 0,10) 
UNION ALL 
( SELECT colum2 as selected_column from my_table 
    WHERE column2 LIKE '%word%' 
    ORDER BY PID DESC LIMIT 0,10) 

我不知道爲什麼它不適合你

+0

Hassan - 我會寫如$ query =「(...)UNION ALL(...)」嗎? – nickm

+0

是的。整個上面的查詢在字符串中包括括號 – Hassan

+0

明白了。然而,查詢仍然會搜索超出最後10行 - 基本上是整個表。是我的while()也許是問題? – nickm