我有点卡在我正在做的一些代码上。
这是我已有的代码
HTML code:
<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进行排序。第一个排序框工作,我可以使用$ sortby按网站点击,ID等排序。
我已经使用选择下拉列表传递了$country
,但我不知道如何将其实现到我的选择查询中。如果某个国家/地区尚未被选中,我需要它来显示所有条目。选择国家/地区后,只显示该国家/地区。
非常感谢任何帮助
答案 0 :(得分: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");
答案 1 :(得分: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