PHP - Order/sort Mysql Results
Hi guys, Having problems sorting mysql results. I can easily order/sort table columns but would like to order the results by a variable.(Distance in Miles).
Havent much experience in PHP and really struggling with this. Basically a query echoing out car make and models and how far they are located from a postcode. Can get it to work no porblem, but not to order/sort by least distance. Heres what i'm working with: Code: [Select] $res=mysql_query("SELECT * FROM cars"); while ($row = mysql_fetch_assoc($res)){ echo $row['Make']; echo $row['Model']; //variable will be determimed by user input form $postcode="W12 3SR"; $start=$postcode; $ends = array(); //finds value from database field { $ends[]=$row['Location']; } // Postcode entered by user via input form $result=mysql_query("SELECT * FROM postcodes WHERE Pcode='$start'"); while($row=mysql_fetch_array($result)){ $gridn[0]=$row['Grid_N']; $gride[0]=$row['Grid_E']; } foreach($ends as $fin){ // Postcodes within mysql table $result=mysql_query("SELECT * FROM postcodes WHERE Pcode='$fin'"); while($row=mysql_fetch_array($result)){ $gridn[1]=$row['Grid_N']; $gride[1]=$row['Grid_E']; } // TAKE GRID REFS FROM EACH OTHER TO WORK OUT DISTANCE. $distance_n=$gridn[0]-$gridn[1]; $distance_e=$gride[0]-$gride[1]; // CALCULATE THE DISTANCE BETWEEN THE TWO POSTCODES AND DIVIDE BY 1.6 TO CONVERT KM TO MILES $hypot=sqrt(($distance_n*$distance_n)+($distance_e*$distance_e))/1.609; //VARIABLE FOR DISTANCE AND ROUNDED OF TO NEAREST WHOLE NUMBER. $distance=''.round($hypot/1000,0).''; echo " $distance miles"; echo "<br>"; } } ?> I wish i could just do something like this but isnt possible, is it ? Code: [Select] "Select * FROM cars ORDER BY $distance"; Thanks! Similar TutorialsHi guys, I have this SQL query which I use in my PHP search script Code: [Select] $query_for_result=mysql_query("SELECT * FROM customer WHERE c_name like '%".$query."%' OR c_telephone like '%".$query."%' OR c_address like '%".$query."%'"); It works fine, the only problem is now my database is bigger I would like to be able do SORT or ORDER BY id so that my search results are in order from asc to desc. Is this possible? if so can you help me. Thanks Hi All i am wanting a column list like this http://extensions.joomla.org/extensions basically the database is set up as (id, category, parent) I want the parent to group the category section and list like the the joomla example in three columns search various threads throughout the internet but none seem to cover this entirely can any one please help????? What im trying to achieve is a user contact system, when the user types input in the textarea its saved in a database along with his userid on the site and the date, I have an admin side coded up where it retrieves the data, but there is no order. I want to have it display the most recent results on top. I have looked into this in the mysql manual, but you know how that is its so hard to make sense of anything in that damn manual. Im using a while loop to display the data. How can I achieve this? For some reason every time I run this form it inserts an undefined value into the field called sortorder into my database table. The rest of the form inputs insert properly but that one. Here's the necessary coding. Anyone see why? form page <?php // Include the database page require ('../inc/dbconfig.php'); ?> <script type="text/javascript"> $(document).ready(function() { $('div.message-error').hide(); $('div.message-success').hide(); $("input.submit").click(function() { $('div.message-error').hide(); var charactername = $("input#charactername").val(); if (charactername == "") { $("div.message-error").show(); $("input#charactername").focus(); return false; } var charactershortname = $("input#charactershortname").val(); if (charactershortname == "") { $("div.message-error").show(); $("input#charactershortname").focus(); return false; } var sortorder = $("input#sortorder").val(); if (sortorder == "") { $("div.message-error").show(); $("input#sortorder").focus(); return false; } var style = $("select#style").val(); if (style == "") { $("div.message-error").show(); $("select#style").focus(); return false; } var status = $("select#status").val(); if (status == "") { $("div.message-error").show(); $("select#status").focus(); return false; } var alignment = $("select#alignment").val(); if (alignment == "") { $("div.message-error").show(); $("select#alignment").focus(); return false; } var division = $("select#division").val(); if (division == "") { $("div.message-error").show(); $("select#division").focus(); return false; } var dataString = 'charactername=' + charactername + '&charactershortname=' + charactershortname + '&sortorder=' + sortorder + '&style=' + style + '&status=' + status + '&alignment=' + alignment + '&division=' + division + '&submitcharacter=True'; $.ajax({ type: "POST", url: "processes/character.php", data: dataString, success: function() { $('div.message-error').hide(); $("div.message-success").html("<h6>Operation successful</h6><p>Character " + charactername + " saved successfully.</p>"); $("div.message-success").show().delay(10000).hide("slow"); $(':input','#characterform') .not(':submit') .val('') return true; } }); return false; }); }); </script> <!-- Form --> <form action="#" id="characterform" > <fieldset> <legend>Add New Character</legend> <div class="field required"> <label for="charactername">Character Name</label> <input type="text" class="text" name="charactername" id="charactername" title="Character Name"/> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="charactershortname">Character Short Name</label> <input type="text" class="text" name="charactershortname" id="charactershortname" title="Character Short Name"/> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="sortorder">Sort Order</label> <select class="dropdown" name="sortorder" id="sortorder" title="Sort Order"> <option value="0">- Select -</option> <?php $sortorder = array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0-9"); foreach($sortorder as $so): ?> <option value="<?php echo $so; ?>"><?php echo $so; ?></option> <?php endforeach; ?> </select> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="style">Character Style</label> <select class="dropdown" name="style" id="style" title="Style"> <option value="0">- Select -</option> <?php $query = 'SELECT id, stylename FROM styles LIMIT 2'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['stylename']."</option>\r"; } ?> </select> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="status">Character Status</label> <select class="dropdown" name="status" id="status" title="Status"> <option value="0">- Select -</option> <?php $query = 'SELECT id, statusname FROM statuses'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['statusname']."</option>\r"; } ?> </select> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="alignment">Alignment</label> <select class="dropdown" name="alignment" id="alignment" title="Alignment"> <option value="0">- Select -</option> <?php $query = 'SELECT id, alignmentname FROM alignments'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['alignmentname']."</option>\r"; } ?> </select> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <div class="field required"> <label for="division">Division</label> <select class="dropdown" name="division" id="division" title="Division"> <option value="0">- Select -</option> <?php $query = 'SELECT id, divisionname FROM divisions'; $result = mysqli_query ( $dbc, $query ); // Run The Query while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) { print "<option value=\"".$row['id']."\">".$row['divisionname']."</option>\r"; } ?> </select> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <input type="submit" class="submit" name="submitcharacter" id="submitcharacter" title="Submit Character" value="Submit Character"/> </fieldset> </form> <!-- /Form --> <!-- Messages --> <div class="message message-error"> <h6>Required field missing</h6> <p>Please fill in all required fields. </p> </div> <div class="message message-success"> <h6>Operation succesful</h6> <p>Character was added to the database.</p> </div> <!-- /Messages --> validation page <?php // Include the database page require ('../inc/dbconfig.php'); if (isset($_POST['submitcharacter'])) { $charactername = mysqli_real_escape_string($dbc, $_POST['charactername']); $charactershortname = mysqli_real_escape_string($dbc, $_POST['charactershortname']); $sortorder = mysqli_real_escape_string($dbc, $_POST['sortorder']); $style = mysqli_real_escape_string($dbc, $_POST['style']); $status = mysqli_real_escape_string($dbc, $_POST['status']); $alignment = mysqli_real_escape_string($dbc, $_POST['alignment']); $division = mysqli_real_escape_string($dbc, $_POST['division']); $query = "INSERT INTO `characters` (charactername, charactershortname, status_id, style_id, division_id, alignment_id, sortorder, creator_id, datecreated) VALUES ('$charactername','$charactershortname','$status','$style','$division', '$alignment', '$sortorder', 1, NOW())"; mysqli_query($dbc, $query) ; } ?> Hi, I have a loop which creates an array: $productions[] = array( 'url'=>get_the_permalink(), 'year'=>$production_year->name, 'title'=>get_the_title() ); When I output the results, the year is in the wrong order:
2019 What I can't work out is how to order 2014 - 2020 I tried ksort(array, SORT_STRING) and ksort(array, SORT_NUMERIC) I also tried natsort But still have the same issue - am I missing something? Thanks Hey guys, I am having trouble figuring this out. I currently have a database that automatically sorts itself by the id of the data. But, I am wanting the user to be able to change the sort order via a select box. I already have the select box programmed with the options, but I am not sure how to go about coding the options to change the sort order of the displayed data. What would the best way to go about programming this be? Thank you very much ahead of time!! I am retrieving data using AJAX. I would like to sort them from newest to oldest date. Currently they show from oldest to newest. How do I do that? <div id="output"></div> <script> $(document).ready(function(){ $.ajax ({ type: 'GET', url: "https://3rdpartywebsite.com/api/getcustomers", dataType: 'json', success: function(data) { $.each(data, function(i, v) { var customerId = v.customerId; var firstName = v.firstName; var lastName = v.lastName; var createdDateTime = v.createdDateTime; $('#output').append('<ul class="output-ul">' + '<li>' + customerId + '</li>' + '<li>' + firstName + '</li>' + '<li>' + lastName + '</li>' + '<li>' + createdDateTime + '</li>' + '</ul>'); }); } }); }); </script>
I am running a script to retrieve numerical value from a webpage, the script echoes the numbers. However I need to add all the numbers to an array or txt file and then have them sorted from highest value to lowest value. Any hints or tips to how I would achieve this? I'm trying to make a function which will display the top X results of the row Y which I set, for this instance I'm using the row browser and the top 5 results from my table statistics, the where is just to eliminate Search Bot results from showing up. I also want it to return the count of the amount of rows as well. So say there was 10 results for the browser 'Safari', then it would return the count of 10 for that result as well as the result itself. Code: [Select] $display->show_list('statistics', 'browser', '5', 'WHERE browser!=\'Search Bot\''); Here is my function. I'm cleaned it up a bit to remove certain checks and outputs if the query were to fail, etc. Code: [Select] function show_list($table, $row, $limit = 5, $where = NULL) { $item = mysql_query("SELECT DISTINCT $row FROM $table $where LIMIT $limit"); $result = array(); while ($fetch = mysql_fetch_array($item)) { $result[] = $fetch; } return $result; } Basically, how would I go about making it count the amount of rows for the row I've set, and then to output that along side the result? Hi Guys I have a product page in mysql as below: id itemnumber order_id 1 348939012 2 2 535432454 1 3 543253424 4 4 987698769 3 I need to order this in my PHP mysql_fetch_assoc by order id. What I mean is I need to list them by order_id: 1,2,3,4 I have used ORDER BY order_id but still it wont work, any ideas? How do I present these documentaries like this:
0-9
10 Things You Need to Know About Sleep
20 Animals That Will Kill You
A
Ant Kingdom
Atkins Diet
B
Battle of the Brains
Body Talk
I don't even know where to start!
I'm not asking anyone to do this for me; I just need a push in the right direction.
Any help will be appreciated.
Here's the query: Code: [Select] $sql = mysql_query("SELECT * FROM resources WHERE gameCat = '' ORDER BY systemCat,order_id"); I want something to happen when the systemCat changes in the results. Like this: Code: [Select] if($row['systemCat'] CHANGES){ echo '<div id="seperator"></div>'; } Any ideas? Thank you! I wish to order my results by its occurrence inside the $status array. Basically all of the results with the status 'New' are to be listed first, then the results with the status Today, Tomorrow, Soon and so on. Is this possible, or is there alternatively a different approach to ordering my results how I desire? Code: [Select] $status = array('New', 'Today', 'Tomorrow', 'Soon', 'Future', 'Complete'); $display->get_results("SELECT * FROM todo ORDER by status DESC"); How can I make this output in descending order from greatest to least? Right now, it appears like: 1940 1941 1942 1943 1944 etc... i'd like it to be like 2012 2011 2010 2009 etc.. until it gets to 1940 any ideas? here is my code: <? $i = 1939; while ($i < 2012) { $i++; echo '<option value="'.$i.'">'.$i.'</option>'; } ?> Hello dear Community, i have a large document - and i want it to parse it and spit out only this part: schule.php?schulnr=80287&lschb= Question: How to i parse the stuff!? Well i try it with FireBug and FirePath (the Xpath-tool) i do it like the following: * Load the document into my browser, if possible * start Firebug extension/add-on * run the FirePath extension * and run the xpath //a[contains(@href, "schule")]/@href * then i click "Eval" button. i find 2030 results - that are marked - how do i get them out of the firebug - to work with them?! If i have to be more precise - please let me know!! Perhaps i have to write more - and to add more information See the screenshot - here http://img259.imageshack.us/img259/7360/sceenshoteval5.jpg how can i copy and paste the results - in order to do further processing from thereon. look forward to hear from you regards How to sort data from table? Currently its sorted by ID. But I want to add option that admin can sort data (click on up/down link or whatever). Its about forum script and all forums have categories. Forum and categories are in same table. Forum "parent" is ID of category. So i have following sorting: Cat1 [ID1] ->Forum1 [ID2] [PARENT1] ->Forum2 [ID3] [PARENT1] Cat2 [ID4] ->Forum3 [ID5] [PARENT2] ->Forum4 [ID6] [PARENT2] I need to add additional field "sort". On click admin can UPDATE sorting by increasing/decreasing number. But problem is categories and forum are in same table. If I want to move up FORUM1 (ID2) with (for example) "sort" number 2 I must decrease number (-1) and that forum will be with same sort number as category above. Also if I want to move Category up/down it also must move all forums from that category (but that is not big problem). What is best way to solve this? Say I have a column in a MySQL database, that contains the following data (each piece of data is in its own row, as stored as a string): 16b 166 13A 13a 4 402c A66 A66b Currently the list sorts as follows: A66 A66b 13A 13a 16b 166 4 402c I need it to sort as follows: A66 A66b 4 13a 13A 16b 166 402c So that any strings that start with a letter are first, followed by numbers in numerical order, with lower case letters coming before upper case letters. This is a huge issue on my website, which has a database of over 35k such numbers, split up into lists. I can't get these sorted properly. At least it would be nice to sort as follows: 1 4 100 344 Instead of 1 100 344 4 Know what I mean? I know that this is complicated, because the variables are strings and not numbers, but is there an easy way to do this? So basically I have a database full of players 'items'. Each player has 2 items. and I need to make a circle with these players with only specific items involved. Each circle can only contain 6 players. The items needed to create this circle a pigs spice sugar cows aluminium marble iron lumber wheat water random random so 10 resources are literally needed to create this circle but 12 is needed to make it a 'circle' if you get me. I'd like to note that it is possible that any of these players can have a combination of any of resources listed above. I've created a form that allows people to submit players resources into my mysql database. I heard it was possible that I could code some type of filter/sort code to sort out the players resources from my database automatically into a set that will match what is needed (without any repeat of resources) and having a php code to export it into html format for viewing pleasures. I really have no idea how to go about this in mysql or php. But if somebody could help me out i'd be ever so glad. Also to note: this isn't school work or something. It's from a game I play and i'm just trying to make my job in it easier. I was thinking of maybe a php code that will run through all the possible partners in order to create this set like run through 100s of different sets until the required set is obtained. I heard this is just about possible. Can anyone help me? Looking forward to all the great help around here. Thanks Samuz PS: Each item/resource can only appear once in each circle. Hi guys, I'm trying to sort an array. The array has information about listings. ID, name, info etc. An unrelated set of data also contains the listing ID's and I have made a function to sort this array and show an new order for the ID's. I now need to sort the original array by this new ID order... This snippet shows that the original listings array can be sorted by link_id: sort($this->links, $this->link->link_id); //This works. It sorts links by link ID! In a foeach loop I have created this: $sleeps_array[] = array("ID" => $link->link_id, "Sleeps" => $sleeps); // Makes an array of arrays of a custom field with listing ID. It makes this: array ( 0 => array ( 'ID' => '9', 'Sleeps' => '2', ), 1 => array ( 'ID' => '3', 'Sleeps' => '4', ), 2 => array ( 'ID' => '6', 'Sleeps' => '6', ), ) I can then sort this array of arrays with this function: function compare_sleeps($a, $b){ return strnatcmp($a['Sleeps'], $b['Sleeps']); } # sort alphabetically by name usort($sleeps_array, 'compare_sleeps'); It then gives me a sorted array according to "Sleeps" (as in, the number of people a property can cater for). It has the correct order of ID to then output but how do I organise the original array by ID with this new array? Sounds complicated, I hope you got that! Cheers, RJP1 I have a MySQL table with a list of albums and there is a field called "views" with the number of views each album has received. I'm looking to generate an array of all the albums in the table and sort the array by the number of views (descending). I have a list of functions defined in a ContentController.php file. I created a new function called build_albumlist, which I've pasted below. The function "get_ip_log" already exists and works, and I used it as a template to create the "build_albumlist" function: public function build_albumlist(){ return $this->select_raw("SELECT * FROM albums WHERE deleted = '0' ORDER BY views DESC",array(),'all'); } public function get_ip_log(){ return $this->select_raw("SELECT * FROM sessions ORDER BY ID DESC",array(),'all'); } When I use the function, I get this warning: Warning: mysql_real_escape_string() expects parameter 1 to be string, array given inC:\xampp\htdocs\Controllers\DBController.php on line 10 [font=cabin, 'trebuchet ms', helvetica, arial, sans-serif]The "select_raw" function that I used in "build_albumlist" is defined in the DBController.php file, and is defined as below:[/font] private function clean_array($params){ $final=array(); foreach($params as $param){ $final[]=mysql_real_escape_string($param); } return $final; } public function select_raw($query,$params,$type=''){ $query=str_replace("?","'%s'",$query); $final_query= call_user_func_array('sprintf', array_merge((array)$query, $this->clean_array($params))); if($type==''){ $result=mysql_query($final_query) or die(mysql_error()); return mysql_fetch_assoc($result); } elseif($type=='all'){ $result=mysql_query($final_query) or die(mysql_error()); $final=array(); while($row=mysql_fetch_assoc($result)){ $final[]=$row; } return $final; } Does anyone know why the "build_albumlist" function is generating this warning, while the "get_ip_log" is not? Any help would be great, as I am obviously pretty new to this. |