【问题标题】:PHP: sorting out in a smart coding way?PHP:以智能编码方式进行排序?
【发布时间】:2011-01-21 19:32:36
【问题描述】:

所以我有这个视频部分,但我想为用户提供一个“排序”选项。

排序选项:ALL(sql语句中没有WHERE)、Videoklips(WHERE SCtry = 0)、SC try(WHERE SCtry = 1)

现在,我知道如何以“我的”方式去做。我会在 index.php 上放置链接: ?sort=video?sort=SCtry

然后制作 2,如果排序视频,如果排序 sctry 然后立即将整个 index.php(显示所有内容)复制到 2 个 if 中,然后只需编辑 SQL 语句 SELECT,在 ?sort=video 上使用 WHERE SCtry = '0',在 ?sort=video 上使用 WHERE SCtry = '1'?排序=SCtry。

现在,我知道如何整理,但我想以更智能的方式对其进行编码(当然,如果它存在的话),因为这似乎太多了,无法复制整个网站然后只更改 1 行...

我要复制的 index.php 示例:

<?php 
$hent_meetup = mysql_query("SELECT * FROM member_film ORDER BY id DESC LIMIT 0,200") or die(mysql_error()); 
while($vis = mysql_Fetch_array($hent_meetup)) { 
?> 

【问题讨论】:

  • 几个问题:您没有使用 smarty 模板引擎,是吗?如果正确,请删除 smarty 标签。下一个;复制 index.php 到底是什么意思?您能否简要说明您要复制的代码?
  • 请发布一些示例代码,以便我们向您展示相同代码的反例。
  • 好的,可以,我不使用 smarty 模板,我现在要删除标签
  • 谢谢阿兹。我认为迈克的回答@@stackoverflow.com/questions/2347833/… 总结得很好。无需复制 index.php。
  • 是的,这很棒,虽然我不知道如果我想在 $sql 行中按 id 排序的话该怎么做.. 如果我这样做,那么排序将不起作用,因为随后 ORDER BY 来了在“哪里”之前

标签: php mysql sorting filtering


【解决方案1】:

没有看到示例代码,我可以告诉你这是我要做的一个示例。

<?
//all of the code before the SQL statement here...
$sql= ' SELECT `column` from `tablename`'; //or any other SQL that is appropriate before the conditional
if(isset($_GET['sort'])){
    if($_GET['sort'] == 'video'){
        $sql .= ' WHERE `SCtry` = 0';
    }elseif($_GET['sort'] == 'SCtry'){
        $sql .= ' WHERE `SCtry` = 1';
    }
}
$sql .= ' ORDER BY `whatever`'; //or any other SQL that is appropriate after the conditional
//rest of code... no need for duplication
?>

已根据 OP 请求进行编辑...

【讨论】:

  • 这很好,正是我所要求的......但是如果我也有 ORDER BY id 怎么办?
  • 我会选择类似 $sort_options = array("video" => " where SCtry = 0", ...); if( isset($sort_options[$_GET['sort']]) ) $sql .= $sort_option[$_GET['sort']];但无论如何使用学说或 zend_db_table 之类的东西会更好
  • 罗曼,我同意。但是,这个问题的性质是如此基本,我想定制答案以使 OP 可以按原样理解和使用代码。
猜你喜欢
  • 1970-01-01
  • 2011-03-30
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-30
  • 2015-03-25
相关资源
最近更新 更多