2014-08-29 65 views
0

我有點卡在一些代碼即將做。

下面的代碼我已經有

HTML代碼:

<form method="post" action="index.php" > 
<select name="sortby" class="sortby" > 
     <option value=" ORDER BY id DESC">Date Added (Newest First)</option> 
     <option value=" ORDER BY id ASC">Date Added (Oldest First)</option> 
     <option value="ORDER BY clicks DESC">Website Clicks </option> 
     <input type="submit" value="Submit" /> 
     </select> 
</form> 
<form method="post" action="index.php"> 
<select name="country" class="sortby"> 
<option value="">Country...</option> 
<option value="AF">Afghanistan</option> 
<option value="AL">Albania</option> 
<option value="DZ">Algeria</option> 
<option value="AS">American Samoa</option> 
<option value="AD">Andorra</option> 
.... and so on 
</select> 
<input type="submit" value="Submit" /> 

PHP代碼:

$sortby = $_POST['sortby']; 
$sortby = $mysqli->real_escape_string($sortby); 
$country = $_POST ['country']; 
$country = $mysqli->real_escape_string($country); 


$results = $mysqli->query("SELECT id, link, image, title, description, country, clicks FROM isc_links WHERE approved=1 $sortby"); 


while($row = $results->fetch_assoc()) { 

    print '<div id="linkmainwrapper"><div id="linkwrapper"><div class="linkimageborder"><div class="linkimage"><a href="http://'.$row["link"].'" target="_blank">'.$row["image"].'</a></div></div>'; 
    print '<div class="linktitle"><a href="clickcounter.php?id='.$row["id"].'" target="_blank">'.$row["title"].'</a></div>'; 
    print '<div class="link">('.$row["link"].')</div>'; 
    print '<div class="countryflag"><img src="http://www.hatblocksdirect.co.uk/lib/flags/'.$row["country"].'.gif"></div>'; 

    print '<div class="linkdescription">'.$row["description"].'</div>'; 
    print '<div class="clickcount">Website Clicks ('.$row["clicks"].')</div></div></div>'; 

我想要做的是排序colums。第一個排序框的作品,我可以通過網站點擊,ID等使用$ sortby排序。

我通過了$country使用選擇下拉菜單,但我不知道如何實現這個到我的選擇查詢。如果一個國家沒有被選中,我需要它顯示所有條目。一旦一個國家被選中,只會顯示該國家。

任何幫助非常感謝

回答

0

WHERE子句的附加條件中的可變取決於參數是否被供給。

if (!empty($_POST['country'])) { 
    $country = "AND country = '" . $mysqli->real_escape_string($country) . "'"; 
} else { 
    $country = ""; 
} 

$results = $mysqli->query("SELECT id, link, image, title, description, country, clicks FROM isc_links WHERE approved=1 $country $sortby"); 
+0

感謝這個偉大的工作。正是我想要做的。 – 2014-08-29 09:00:18

0

使用的if條件像

if(isset($_POST ['country'])) 
{ // if country is set 
    $country = $mysqli->real_escape_string($_POST ['country']); 
    $sql="SELECT id, link, image, title, description, country, clicks FROM isc_links WHERE approved=1 and country='$country' $sortby"; 
} 
else 
{ // if country is not se 
    $sql="SELECT id, link, image, title, description, country, clicks FROM isc_links WHERE approved=1 $sortby"; 
} 
$results = $mysqli->query($sql); // execute the query