我有一个简单的列表类型的php页面,它根据mysql查询列出项目,如:
mysql_select_db($database_connBHN, $connBHN);
$query_rsMarket = "SELECT * FROM my_items WHERE active=1 ORDER BY name asc";
$rsMarket = mysql_query($query_rsMarket, $connBHN) or die(mysql_error());
$row_rsMarket = mysql_fetch_assoc($rsMarket);
$totalRows_rsMarket = mysql_num_rows($rsMarket);
然后页面将这些项目及其描述列在单独的表中。
最初,此页面按字母顺序列出这些项目。现在我想在页面顶部放置一个下拉框,用户可以选择另外两到三个排序选项,如date或itemId等,这些值存储在数据库中。
如何在不离开该页面的情况下以简单的方式解决这个问题? (即我不想为每个不同的结果集创建单独的页面)
答案 0 :(得分:1)
不,将此作为单个脚本保留更容易,只允许切换排序变量。出于安全考虑,最好将用户输入限制为PHP脚本中的每个定义的选项集:
$sort_options = array('name asc','name desc','dateadded asc','dateadded desc');
if(!isset($_GET['field'])){
$_GET['field'] = 'name';
}
if (!isset($_GET['order'])){
$_GET['order'] = 'asc';
}
$full_query_sort = $_GET['field'].' '.$_GET['order'];
if (!in_array($full_query_sort,$sort_options)){
die('invalid selection');
}
mysql_select_db($database_connBHN, $connBHN);
$query_rsMarket = "SELECT * FROM my_items WHERE active=1 ORDER BY ".$full_query_sort;
$rsMarket = mysql_query($query_rsMarket, $connBHN) or die(mysql_error());
$row_rsMarket = mysql_fetch_assoc($rsMarket);
$totalRows_rsMarket = mysql_num_rows($rsMarket);
现在您可以使用_GET变量设置顺序:http://example.com/page.php?field=name&order=desc
等。可以使用下拉菜单使用javascript(或表单提交)设置:
<select id='field_select'
name='field'
onchange="window.location='?field='+this.value+'&order='+document.getElementById('order_select').value;">
<option value='name' <?php if(!isset($_GET['field']) || $_GET['field']=='name'){echo "selected";} ?>>Sort by Name</option>
<option value='dateadded' <?php if(isset($_GET['field']) && $_GET['field']=='dateadded'){echo "selected";} ?>>Sort by Date Added</option>
</select>
<select id='order_select'
name='order'
onchange="window.location='?field='+document.getElementById('field_select').value+'&order='+this.value;">
<option value='asc' <?php if(!isset($_GET['order']) || $_GET['order']=='asc'){echo "selected";} ?>>Ascending/option>
<option value='desc' <?php if(isset($_GET['order']) && $_GET['order']=='desc'){echo "selected";} ?>>Decending</option>
</select>