PHP/SQL: Reverse order in SQL sentence.

<?php $sql = 'select fielda, fieldb, fieldc from table1 order by field, fieldb, fieldc union all select field1, field2, field3 from table2 order by field1, field2 desc, field3 asc'; print_r($sql2 = invert_order($sql)); function invert_order($str){ $re = '/(?<=order\sby\s)(.*)(?=)/mi'; preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0); $mat = $matches[sizeof($matches)-1]; //-- get only last order field list $mat=$mat[sizeof($mat)-1]; $mat=explode(",",$mat); for($i=0; $i<sizeof($mat); $i++){ //-- reverse each pair of order field/direction $duet = preg_split("/\s+/", trim($mat[$i])); if (sizeof($duet)<2) $duet[1]=""; switch(strtolower($duet[1])) { case "desc": $duet[1] = "asc"; break; default: $duet[1] = "desc"; break; } $mat[$i] = implode(" ",$duet); } $re2 = '/(order\s+by\s+.*)*$/i'; //-- replace last order by with new inverted order by: $subst = "order by ".implode(", ",$mat); $result = preg_replace($re2, "", $str); return $result . " $subst"; } ?>
Function to reverse order of SQL standard "select" sentence.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.