Предварительный заказ по php в выпадающем скрипте

0

Я использую PHP-скрипт для создания множественного раскрывающегося списка, и у меня возникают проблемы в этой области. Я хочу поставить ORDER BY, но я не знаю, где его поставить:

// define a string with the WHERE condition, and then the SELECT query
$where = isset($ar_where) ? ' WHERE '. implode($ar_where, ' AND') : '';
$sql = "SELECT DISTINCT '$col' FROM '$table'".$where;

вот код. Я стараюсь делать это так

$sql = "SELECT DISTINCT $col FROM $table".$where." ORDER BY 'make' DESC"; 

но ничего не происходит, пытаясь сделать машину в алфавитном порядке

    // Here add the name of the table and columns that will be used for select lists, in their order
// Add null for 'links' if you don't want to display their data too
$table = 'cars';
$ar_cols = array('year', 'make', 'model', 'null');

$preid = 'slo_';        // a prefix used for element ID, in which Ajax will add <select>
$col = $ar_cols[0];     // the variable used for the column that wil be selected
$mine = $ar_cols[1];
$re_html = '';          // will store the returned html code

// if there is data sent via POST, with index 'col' and 'wval'
if(isset($_POST['col']) && isset($_POST['wval'])) {
  // set the $col that will be selected and the value for WHERE (delete tags and external spaces in $_POST)
  $col = trim(strip_tags($_POST['col']));
  $wval = "'".trim(strip_tags($_POST['wval']))."'";
}

$key = array_search($col, $ar_cols);            // get the key associated with the value of $col in $ar_cols
$wcol = $key===0 ? $col : $ar_cols[$key-1];     // gets the column for the WHERE clause
$_SESSION['ar_cols'][$wcol] = isset($wval) ? $wval : $wcol;    // store in SESSION the column and its value for WHERE

// gets the next element in $ar_cols (needed in the onchange() function in <select> tag)
$last_key = count($ar_cols)-1;
$next_col = $key<$last_key ? $ar_cols[$key+1] : '';

$conn = new mysqli($server, $user, $pass, $dbase);     // connect to the MySQL database

if (mysqli_connect_errno()) { exit('Connect failed: '. mysqli_connect_error()); }     // check connection

// sets an array with data of the WHERE condition (column=value) for SELECT query
for($i=1; $i<=$key; $i++) {
  $ar_where[] = '''.$ar_cols[$i-1].''='.$_SESSION['ar_cols'][$ar_cols[$i-1]];
}

// define a string with the WHERE condition, and then the SELECT query
$where = isset($ar_where) ? ' WHERE '. implode($ar_where, ' AND') : '';
//$sql = "SELECT DISTINCT '$col' FROM '$table'".$where; 
$sql = "SELECT DISTINCT $col FROM $table".$where." ORDER BY 'make' DESC";

$result = $conn->query($sql);       // perform the query and store the result

// if the $result contains at least one row
if ($result->num_rows > 0) {
  // sets the "onchange" event, which is added in <select> tag
  $onchg = $next_col!==null ? " onchange=\"ajaxReq('$next_col', this.value);\"" : '';

  // sets the select tag list (and the first <option>), if it not the last column
  if($col!=$ar_cols[$last_key]) $re_html = ucfirst($col). ': <select name="'. $col. '"'. $onchg. '><option>- - -</option>';

  while($row = $result->fetch_assoc()) {
    // if its the last column, reurns its data, else, adds data in OPTION tags
    if($col==$ar_cols[$last_key]) $re_html .= '<br/>'. $row[$col];
    else $re_html .= '<option value="'. $row[$col]. '">'. $row[$col]. '</option>';
  }

  if($col!=$ar_cols[$last_key]) $re_html .= '</select> ';        // ends the Select list
}
else { $re_html = ''; }

$conn->close();

// if the selected column, $col, is the first column in $ar_cols
if($col==$ar_cols[0]) {
  // adds html code with SPAN (or DIV for last item) where Ajax will add the select dropdown lists
  // with ID in each SPAN, according to the columns added in $ar_cols
  for($i=1; $i<count($ar_cols); $i++) {
    if($ar_cols[$i]===null) continue;
    if($i==$last_key) $re_html .= '<div id="'. $preid.$ar_cols[$i]. '"> </div>';
    else $re_html .= '<br><span id="'. $preid.$ar_cols[$i]. '"> </span>';
  }

  // adds the columns in JS (used in removeLists() to remove the next displayed lists when makes other selects)
  $re_html .= '<script type="text/javascript">var ar_cols = '.json_encode($ar_cols).'; var preid = "'. $preid. '";</script>';
}
else echo $re_html;
  • 1
    ORDER BY следует после WHERE $ sql = "SELECT DISTINCT $col FROM $table ". $ Where. "ORDER BY id ASC";
  • 0
    Также не переносите имена столбцов с помощью апострофа, это будет восприниматься как строка. Используйте взамен `` (backtick), хотя это необязательно.
Теги:
oop

3 ответа

1
Лучший ответ

ORDER BY приходит после WHERE, поэтому ваш код будет выглядеть следующим образом:

// define a string with the WHERE condition, and then the SELECT query
$where = isset($ar_where) ? ' WHERE '. implode($ar_where, ' AND') : '';
$sql = "SELECT DISTINCT '$col' FROM '$table'".$where." ORDER BY YOUR_COL_HERE ASC";

Вы можете использовать ASC или DESC зависимости от того, хотите ли вы восходящий или нисходящий порядок.

0

SQL Ключевое слово ORDER BY должно быть в конце вашего запроса.

0

ORDER BY всегда является последней версией SQL. Иногда вы также заметите, что в некоторых SQL-запросах есть ORDER BY ORDER, которые являются ASC DESC (по возрастанию или по убыванию); если вы хотите добавить, что можете. Например,

 WHERE UserID = 1 AND ORDER BY FirstName DESC

Я бы изменил ваш код ниже:

// define a string with the WHERE condition, and then the SELECT query
$where = isset($ar_where) ? ' WHERE '. implode($ar_where, ' AND') : '';
// replace SoftField1 with the field you want to sort it by, 
// you may want to add ASC or DESC after the SortField1/2 if you 
// want a certain order
$order_by = ' ORDER BY 'SortField1', 'SortField2'';
$sql = "SELECT DISTINCT '$col' FROM '$table'".$where.$order_by;

Ещё вопросы

Сообщество Overcoder
Наверх
Меню