2014-10-09 19 views
-1

我在編碼搜索過濾器時遇到了十字路口,而且我甚至不知道實際搜索的措詞。PHP如果值等於「this」 - >什麼都不做,else add ='before and'

我有一個基於SQL生成值的表單,然後我在顯示頁面上使用php來爲SQL搜索格式化這些值。我希望的行爲是在HTML表單中包含一個繞過此特定過濾器以顯示所有產品的選項。我以前的解決方案是包含IS NOT NULL作爲其中一個選項的值,但是在我基於SQL值生成表單數據之前。

這是我最喜歡的行爲,我可以解釋(這不是我的代碼,只是一個編碼解釋)。

if $productnamesort == " IS NOT NULL" -> do nothing (leave value as " IS NOT NULL") 
if $productnamesort != " IS NOT NULL" -> append characters before and after the value (=' before and ' after) 

所以我需要格式化的$ productnamesort輸出基本上是兩件事

1)一個 「IS NOT NULL」
2)= '$ productnamesort'

只是爲了更詳細一點,這裏是相關的代碼片段。

表單輸入

<select class="selectinput" name="filter_product_name"> 
    <option value=" IS NOT NULL" selected>All Products</option> 
    <? 
    $r = mysql_query("select product_name from products"); 
    while($row = mysql_fetch_assoc($r)){ 
    echo "<option value='{$row['product_name']}'>{$row['product_name']}</option>";} 
    ?> 
    </select> 

當前PHP格式(這裏我需要一些幫助)

$productnamesort = $_POST[ 'filter_product_name' ]; 

我知道有多種方式來解決這個問題,如果任何人有什麼更有效的我渴望學習。

謝謝!

回答

0

我不會推薦這樣做。

你可以讓你的表格是這樣的:

<select class="selectinput" name="filter_product_name"> 
<option value="all_products" selected>All Products</option> 
<? 
$r = mysql_query("select product_name from products"); 
while($row = mysql_fetch_assoc($r)){ 
echo "<option value='{$row['product_name']}'>{$row['product_name']}</option>";} 
?> 
</select> 

然後,你可以爲查詢做這樣的事情:

<?php 
if($_POST['filter_product_name'] == 'all_products') { 
    // Query like Select * from products 
} else { 
    // Query like SELECT * FROM products WHERE name = '".$_POST['filter_product_name']."' 
} 

我知道,我的最後一個部分是僞代碼,但你應該能夠弄清楚。

0

這是不使用mysql_*功能件好事,但你可以做到以下幾點:

$productnamesort = $_POST[ 'filter_product_name' ]; 
if ($productnamesort != " IS NOT NULL") 
    $productnamesort = "'".mysql_real_escape_string($productnamesort)."'"; 

一個更好的解決方案是使用mysqli_*PDO功能(mysql_ *已被棄用,將在未來被刪除版本)。

您可以輕鬆地按照mysqli_preparePDO::prepare的官方文檔中給出的示例進行操作。