PHP - Sorting Via A Variable?
Is it possible to sort a table of mysql data, by using a variable?
I'm trying this: Code: [Select] <?php $result = mysql_query("SELECT * FROM members ORDER BY '$totalpower'"); echo "<table border='1' cellpadding='10'>"; echo "<tr> <th>Rank</th> <th>Username</th> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo '<td> </td>'; echo '<td>' . $row['Username'] . '</td>'; echo "</tr>"; } echo "</table>"; ?> It display's a list of username's but not in the correct power order. $totalpower is defined: Code: [Select] <?php //power calculations $result = mysql_query("SELECT * FROM members WHERE Username='$_SESSION[Username]'") or die(mysql_error()); while($row = mysql_fetch_array( $result )) { $power1 = $row['ounit1'] * 50; $power2 = $row['ounit2'] * 70; $power3 = $row['ounit3'] * 110; $power4 = $row['ounit4'] * 200; $power5 = $row['ounit5'] * 150; $power6 = $row['ounit6'] * 300; $power7 = $row['ounit7'] * 500; $power8 = $row['ounit8'] * 450; $power9 = $row['ounit9'] * 650; $power10 = $row['ounit10'] * 350; $power11 = $row['ounit11'] * 600; $power12 = $row['ounit12'] * 1000; $dpower1 = $row['dunit1'] * 50; $dpower2 = $row['dunit2'] * 70; $dpower3 = $row['dunit3'] * 110; $dpower4 = $row['dunit4'] * 200; $dpower5 = $row['dunit5'] * 150; $dpower6 = $row['dunit6'] * 300; $dpower7 = $row['dunit7'] * 500; $dpower8 = $row['dunit8'] * 450; $dpower9 = $row['dunit9'] * 650; $dpower10 = $row['dunit10'] * 350; $dpower11 = $row['dunit11'] * 600; $dpower12 = $row['dunit12'] * 1000; $dbase = $row['baselevel'] * 3000; } $offencepower = $power1+$power2+$power3+$power4+$power5+$power6+$power7+$power8+$power9+$power10+$power11+$power12; $defencepower = $dpower1+$dpower2+$dpower3+$dpower4+$dpower5+$dpower6+$dpower7+$dpower8+$dpower9+$dpower10+$dpower11+$dpower12+$dbase; $totalpower = (($offencepower+$defencepower)/ 100 * 30) + $offencepower+$defencepower; ?> Also how do I add auto numbers in the left column e.g 1. 2. 3. 4. Thanks in advance. Similar TutorialsI got myself wrapped up in something I can't get figured. In the following code, I would like to order the list of properties ("<div class="property">") by the "$pr_street" variable. Any help is appreciated. Thanks, <?php /////////////// SEO /////////////// $keywords = ""; $description = ""; /////////////// DB Connection /////////////////// include('../includes/connect.php'); include('../includes/login.php'); if(isset($_GET['delete'])){ $del_id = $_GET['delete']; $sel_del_imgs_q = "SELECT * FROM pr_imgs WHERE pr_id = '$del_id'"; $pr_img_del_result = mysqli_query($db, $sel_del_imgs_q); while($pr_del_imgs = mysqli_fetch_array($pr_img_del_result)){ $pr_del_img_id[] = $pr_del_imgs['pr_img_id']; $pr_del_img_path_xl[] = $pr_del_imgs['pr_img_path_xl']; $pr_del_img_path_l[] = $pr_del_imgs['pr_img_path_l']; $pr_del_img_path_m[] = $pr_del_imgs['pr_img_path_m']; $pr_del_img_path_s[] = $pr_del_imgs['pr_img_path_s']; $pr_del_img_path_xs[] = $pr_del_imgs['pr_img_path_xs']; } for($i = 0; $i < count($pr_del_img_id);$i++){ if(!empty($pr_del_img_path_xl[$i])){ unlink('..'.$pr_del_img_path_xl[$i]); } if(!empty($pr_del_img_path_l[$i])){ unlink('..'.$pr_del_img_path_l[$i]); } if(!empty($pr_del_img_path_m[$i])){ unlink('..'.$pr_del_img_path_m[$i]); } if(!empty($pr_del_img_path_s[$i])){ unlink('..'.$pr_del_img_path_s[$i]); } if(!empty($pr_del_img_path_xs[$i])){ unlink('..'.$pr_del_img_path_xs[$i]); } } $dir_to_remove = dirname(getcwd()).'/images/properties/'.$del_id; rmdir($dir_to_remove); $delete_query = "DELETE property, pr_imgs FROM property LEFT OUTER JOIN pr_imgs ON property.pr_id = pr_imgs.pr_id WHERE property.pr_id = '$del_id'"; $deleted = mysqli_query($db, $delete_query); if($deleted){ header('Location:index.php'); //print $delete_query; } } $sel_pr_type = 1; // 1 = For Rent Residential, 2 = For Rent Commercial, 3 = For Sale $pr_sel_query = "SELECT * FROM property LEFT OUTER JOIN pr_imgs ON property.pr_id = pr_imgs.pr_id AND pr_imgs.pr_img_count = '0' ORDER BY property.pr_live DESC, property.pr_modified DESC"; $result = mysqli_query($db,$pr_sel_query); while($pr_row = mysqli_fetch_array($result)){ $pr_id[] = $pr_row[0]; $pr_type[] = $pr_row['pr_type']; $pr_live[] = $pr_row['pr_live']; $pr_title[] = $pr_row['pr_title']; $pr_street[] = $pr_row['pr_street']; $pr_city[] = $pr_row['pr_city']; $pr_state[] = $pr_row['pr_state']; $pr_zip[] = $pr_row['pr_zip']; $pr_price[] = $pr_row['pr_price']; $pr_bedroom[] = $pr_row['pr_bedroom']; $pr_bathroom[] = $pr_row['pr_bathroom']; $pr_size[] = $pr_row['pr_size']; $pr_img_path_s[] = $pr_row['pr_img_path_s']; } include('../includes/head.php'); include('../includes/header.php'); ob_end_flush(); // ob_start() in /includes/login.php ?> <div class="content"> <div class="hldr"> <?php if($loggedin){ ?> <div class="left"> <h2><a href="/admin/">Admin</a></h2> <?php for($i = 0; $i < count($pr_id); $i++){ if($pr_live[$i] == 1){ $islive[$i] = ' • <span class="live">Live</span>'; } ?> <div class="property"> <div class="thumb"><a href="/property_details.php?property=<?php print $pr_id[$i]; ?>"><img src="<?php print $pr_img_path_s[$i]; ?>" width="100" height="100" /></a></div> <div class="details"> <h4><a href="/property_details.php?property=<?php print $pr_id[$i]; ?>"><?php print $pr_title[$i]; ?></a></h4> <ul> <li>Bedroom: <?php print $pr_bedroom[$i]; ?> • Bathroom: <?php print $pr_bathroom[$i]; ?></li> <li class="adrs"><?php print $pr_street[$i].', '.$pr_city[$i].', '.$pr_state[$i].' '.$pr_zip[$i]; ?></li> <li>Price: $<?php print $pr_price[$i]; ?> 4 • Size: <?php print $pr_size[$i]; ?> sq ft</li> <li><a href="/admin/add-property.php?edit=<?php print $pr_id[$i]; ?>">EDIT</a> • <a href="/admin/index.php?delete=<?php print $pr_id[$i]; ?>" class="red" onclick="return confirm('Are you sure you want to deletet this Property?');">DELETE</a><?php print $islive[$i]; ?></li> </ul> </div> </div> <?php } ?> </div> <div class="right"> <div class="sidebarHome"> <div class="sidebarHome"> <p><strong><a href="/admin/">Admin Home</a></strong></p> <p><strong><a href="add-property.php">Add Property</a></strong></p> <p><strong><a href="for-rent-res.php">Edit Properties for Rent - Residential</a></strong></p> <p><strong><a href="for-rent-com.php">Edit Properties for Rent - Commercial</a></strong></p> <p><strong><a href="for-sale.php">Edit Properties for Sale </a></strong></p> <p><strong><a href="index.php?logout=1">Log Out </a></strong></p> </div> </div> <div class="clear"> </div> </div> <?php }else { ?> <div class="fullpage"> <div class="login"> <?php print $error_msg; ?> <form method="post" action="index.php"> <label>Username:</label> <input type="text" name="user" class="txt" /> <label>Password:</label> <input type="password" name="pass" class="txt" /><br /> <input type="submit" name="login" value="Login" class="submit" /> </form> </form> </div> </div> <?php } ?> </div> <?php include('../includes/footer.php'); ?> This topic has used a waypoint to get to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=359489.0 How do I like it, you ask? Quite well. Besides the downtime Tuesday I haven't had any server problems, and the game itself is great. Very D2-esque but with very noticeable enhancements. I have an array like this: $array[$row] = array ( 'name' = $name, 'discount' = $discount, 'price' = $price ); Now, I have about 200 of those in that array, and im trying to sort by the discount, highest 1st. How would I go about doing that? Thanks. Part of my code: Code: [Select] <?php $arr = array ("Christina", "Daniel", "Andreea); reset($arr); foreach ($arr as $username) { //more code here ... foreach ($stats as $result) { echo $username."'s points - ".$result."<br />"; } } ?> And gives this: Code: [Select] Christina's points - 14 Daniel's points - 45 Andreea's points 23 My question is: can you sort the the $result so it will show Code: [Select] Daniel's points - 45 Andreea's points 23 Christina's points - 14 Thank you Just a further question from a earlier post that was complete if i do a search and i want to order them from a drop box the if statement would it just look like Quote "select * from Table order by '".$_POST['order']."'" Or would this not work ? Thanx Hello. I have a multi dimensional array that needs to be sorted. Array top25 [index][product id][number_of_purchases]. The index will contain a unique number for each product id. First product will be 1, second product will be 2, etc. The product id will be a id number like 34324ac9a89. The number of purchases will be how many times the item has been purchased. - End result: I want to print the 25 most purchased products in this format. product id - number of purchases a39acz - 503 a8cz9c - 480 zc8ac - 392 How do I do this? Thanks I have a situation where I need to sort files on a screen based on the date that is embedded into the file name. The problem is that I am sorting based off the file name, and when I get my output the LEGACY file always comes out on top of the sort because it starts with a 0 meanwhile the rest have dates appended the the filename so I don't have a problem sorting those. Please help me if you can. <? //Special case for extra files IF($Recordmyrow['App'] == "(Printable)") { $display = false; $column3 = "Printable VER"; IF($securityvalue == "P") { if(substr($path, 0, 5) == "file:") { $filename = substr($path, 5); if(file_exists($filename)) { $basename = substr($filename, 0, strrpos($filename, '.')); $ext = ".pdf"; $allfiles = glob("{$basename}*.pdf"); rsort($allfiles, SORT_NUMERIC); foreach($allfiles as $file) { if($ext == ".pdf") { $column4 = "<a href=\"pdf.php?src={$file}\">VIEW</a><br />\n"; $codate = substr($file, 70, 8); $co = substr($file, 59, 1); if ($codate != "pdf") { $column3 = "Printable File - ".$codate; } elseif ($codate == "pdf") { $column3 = "Printable File - LEGACY"; } IF($lastGroup != $Recordmyrow['Grouping']) { $lastGroup = $Recordmyrow['Grouping']; ?> <TR> <TD colspan="4" align="center" bgcolor="#418765"><B><FONT color="white"><? echo $Recordmyrow['Grouping'] ?></FONT></B></TD> </TR> <? } ?> <TR> <TD class="display" align="center" bgcolor="<?=changeColor($rowcount)?>"><B><? echo $column1 ?></B></TD> <TD class="display" bgcolor="<?=changeColor($rowcount)?>"><B><? echo $column2 ?></B></TD> <TD class="display" bgcolor="<?=changeColor($rowcount)?>"><B><? echo $column3 ?></B></TD> <TD class="display" bgcolor="<?=changeColor($rowcount)?>" align="center"><B><? echo $column4 ?></B></TD> </TR> <? $rowcount++; } } } else { $column4 = "Not Available"; ?> <TR> <TD class="display" align="center" bgcolor="<?=changeColor($rowcount)?>"><B><? echo $column1 ?></B></TD> <TD class="display" bgcolor="<?=changeColor($rowcount)?>"><B><? echo $column2 ?></B></TD> <TD class="display" bgcolor="<?=changeColor($rowcount)?>"><B><? echo $column3 ?></B></TD> <TD class="display" bgcolor="<?=changeColor($rowcount)?>" align="center"><B><? echo $column4 ?></B></TD> </TR> <? $rowcount++; } } } } i need to sort my database results by the day they were added to the database. There is a column with the timestamp of when they were inserted but how do i group them by the day they were inserted so i can display them as such: Mon 14th: 5 records Tues 15th: 11 records etc. Here is the code: Code: [Select] <table class="sortable"> <?php while($row = mysql_fetch_array($result)) { $title = $row["Rim"]; $model = $row["model"]; $dimenzija = $row["Dimenzija"]; $ime = $row['name']; $cena = $row['price']; $cena = number_format($cena, 2, ',', '.'); $id = $row['product_id']; if($i == 0) echo "<tr>"; echo "<td>" ?><a href="index.php?route=product/product&product_id=<?php echo $id?>"><?php echo $model ?></a> <?php echo "<br>$dimenzija<br>$ime<br>"; ?> <span style="color: #900; font-weight: bold;"><?php echo $cena . "din"?> </span> <?php echo "</td>"; if(++$i == $max_columns) { echo "</tr>"; $i=0; } }} if($i > 0) { for($j=$i; $j<$max_columns;$j++) echo "<td> </td>"; echo "</tr>"; } $prev = $start - $per_page; $next = $start + $per_page; if (!($start<=0)){ echo "<a href='{$_SERVER['PHP_SELF']}&start=$prev'>Prethodna strana </a>"; } $page = 1; for($x=0;$x<$record_count;$x=$x+$per_page){ if($start != $x){ echo " <a href='{$_SERVER['PHP_SELF']}&start=$x'> $page </a> ";} else{ echo " <a href='{$_SERVER['PHP_SELF']}&start=$x'> <b>$page</b> </a> ";} $page++; } if (!($start>=$record_count - $per_page)){ echo "<a href='{$_SERVER['PHP_SELF']}?route=product/search&start=$next'> Sledeća strana</a>"; } ?> </table> How can i create sorting button? Is it possible to do it without javascript (I am new to PHP and JS is still unknown to me)? Hello, i need some help with sorting arrays by it's value. lets say i want to have two different html tables listing the employees and another for the managers, then i want to sort them by Group ID's: Etc: Workers as the key / 1 as the value. Groups: Workers => 1 Managers => 2 Workers Group ID John 1 Peter 1 Lance 1 Managers Group ID Carol 2 Greg 2 Brian 2 How can i do this? How to sort PHP2d Array using upon key. eg. I have a array of $users[0]['name'] = "abc" $users[0]['age'] = "12" $users[0]['sex'] = "M"; $users[1]['name'] = "xyz" $users[1]['age'] = "15" $users[1]['sex'] = "M"; $users[2]['name'] = "pqr" $users[2]['age'] = "16" $users[2]['sex'] = "F"; Now I have to sort in on age or 'sex', Hi - I'm modifying some PHP code that someone else wrote. Below is a snippet of code that basically takes mp3 files files within all the folders in a directory, and creates an RSS feed. In the resulting feed, the files are intermingled in date order. Instead, I'd like them sorted by the directory that they are in. So, if there are files in these directories: 01-First 02-Second 03-Third I'd like all the files in the "01-First" directory to come before the "02-Second" directory and so on. Within each directory the files can be sorted as they currently are. The name of the directory in the code is signified by $dir_name. I tried sort() and array_multisort() but I couldn't get either of them to work the way I wanted. Any thoughts? if ($url_params['mode'] == 'rss2') { print getRSSHeader('UTF-8', $device, $vm_config, $vm_name, $web_master, $logo_image,$context); $mailboxes = array(); if ($dev_dir = @opendir($VMHome . $device)) { //might fail if mailbox has not received first message yet while ($f = readdir($dev_dir)) { if (!eregi("tmp","$f") && !eregi("\.+","$f") && !eregi("Exclude-From-CD", "$f")) { //skip tmp directory and Exclude-From-CD Directories array_push($mailboxes,"$f"); #collect all existing mailboxes } } array_multisort($mailboxes, SORT_DESC); foreach ($mailboxes as $mailbox) { $files=array(); $dir_name = $VMHome . $device . '/'. $mailbox .'/'; $dir = opendir($dir_name); while ($f = readdir($dir)) { if (eregi("\.txt",$f)){ #if filename matches .txt in the name array_push($files,"$f"); #push into $files array } } foreach($files as $file){ $props = getProperties($dir_name, $file); $uid = getMP3File($dir_name, $file, $props, $device, $mailbox, $vm_config, $vm_name,$context); print getRSSItem ($props, $uid, $dir_name, $device, '/' . $mailbox . '/', $context); } } } print ' </channel> </rss>'; } I have the following php array structure and couldnot able to sort it according to the overall points. My code is reading an xml file using simplexml. Any help would be appreciated. Array ( => SimpleXMLElement Object ( [played] => 0 [won] => 0 [drawn] => 0 [lost] => 0 [overallpoints] => 0 ) [1] => SimpleXMLElement Object ( [played] => 6 [won] => 3 [drawn] => 0 [lost] => 3 [overallpoints] => 9 ) [2] => SimpleXMLElement Object ( [played] => 3 [won] => 1 [drawn] => 0 [lost] => 2 [overallpoints] => 3 ) [3] => SimpleXMLElement Object ( [played] => 0 [won] => 0 [drawn] => 0 [lost] => 0 [overallpoints] => 0 ) [4] => SimpleXMLElement Object ( [played] => 2 [won] => 1 [drawn] => 0 [lost] => 1 [overallpoints] => 3 ) } I have an array that looks like this... Code: [Select] Array ( [0] => Array ( [0] => 2 [1] => Dylan Cross ) [1] => Array ( [0] => 5 [1] => Bob Smith ) [2] => Array ( [0] => 1 [1] => Sarah Park ) [3] => Array ( [0] => 7 [1] => Jane Knowles ) [4] => Array ( [0] => 6 [1] => Harry Hill ) [5] => Array ( [0] => 3 [1] => Jack Rock ) ) How do I sort this array so it is ordered alphabetically by the names so the result will be... Code: [Select] Array ( [0] => Array ( [0] => 5 [1] => Bob Smith ) [1] => Array ( [0] => 2 [1] => Dylan Cross ) [2] => Array ( [0] => 6 [1] => Harry Hill ) [3] => Array ( [0] => 3 [1] => Jack Rock ) [4] => Array ( [0] => 7 [1] => Jane Knowles ) [5] => Array ( [0] => 1 [1] => Sarah Park ) ) Thanks I am using the following code to sort by Year. It displays the current year fine and current year also displays in selection but does give the option for the previous years selection. Code: [Select] <form action="archivednews.php" method="post"> <select name="year" id="year"> <?PHP for($i=date("Y"); $i<=date("Y"); $i++) if($year == $i) echo "<option value='$i' selected>$i</option>"; else echo "<option value='$i'>$i</option>"; ?> </select> <input type="submit" value="GO"> </form> Hello everyone, Could be possible someone help me on this code please? I need to group and sort $search_query. They are the keywords extracted from $_SERVER[HTTP_REFERER] (referer in the query). Thank you in advance. Code: [Select] $query = ("SELECT referer, browser_ip, date, customers_id, counter, browser_id, browser_language FROM visitors WHERE SUBSTRING(browser_language,1,1) != '[' ORDER by date DESC"); $result = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_array($result)) { $referer = $row[0]; IF($referer) { PREG_MATCH("/[\&\?]q=([^&]*)/", $referer, $matches); $search_query = RAWURLDECODE($matches[1]); $search_query = STR_REPLACE("+", " ", $search_query); } ........................ Hi does anyone know how to sort the array below (files) echo "<br /><br /><b>Favorites</b><br />"; $d = dir("/mnt/disk/v1/mfiles/downloads/music/favorites/"); while (false !== ($entry = $d->read())) { if($entry!='.' && $entry!='..') { if(is_dir($entry)) { echo 'true'; $subdirs = get_leaf_dirs($entry); if ($subdirs) $array = asort(array_merge($array, $subdirs)); else $array[] = $entry; } echo '<a href="/scripts/download.php?actie=favorites/'.$entry.'" title="Click here to download this song" target="_blank">'.left($entry,(strlen($entry)-4)).'</a><br />'; } } $d->close(); Hello, Hope somebody can help me. I have an XML file that is generated by active directory that dumps everything required for a telephone directory. I currently present this using XSL but would like to move towards PHP. I have some rudimentary code and it's working fine but I'd like to be able to sort by various values, such as First Name or telephone number. My XML format looks like this: Code: [Select] <?xml version="1.0" encoding="UTF-8"?> <telephonelist> <employee> <firstname>Jimmy</firstname> <lastname>Jimmerson</lastname> <email>jimbo@companyxyz.com</email> <extensionnum>956</extensionnum> <jobtitle>Security Officer</jobtitle> <department>Security</department> </employee> <employee> <firstname>David</firstname> <lastname>Davidson</lastname> <email>David.Davidson@companyxyz.com</email> <extensionnum>968</extensionnum> <jobtitle>Manager</jobtitle> <department>Management</department> </employee> Any my current code looks like this: Code: [Select] <? $myStaffMembers = new SimpleXMLElement("includes/telephonelist.xml", null, true); echo <<<EOF <table width="95%" border="0"> <tr> <th><b>First Name</b></th> <th><b>Last Name</b></th> <th><b>Telephone Number</b></th> <th><b>Position</b></th> </tr> EOF; foreach($myStaffMembers as $myStaffMember) { echo " <tr> <td>{$myStaffMember->firstname}</td> <td>{$myStaffMember->lastname}</td> <td>{$myStaffMember->extensionnum}</td> <td>{$myStaffMember->jobtitle}</td> </tr>"; } ?> Appreciate any help anybody could give. Thanks, LJ I need to sort this: Code: [Select] customVar($var1, $var2, $var3); I have tried: Code: [Select] sort(customVar($var1, $var2, $var3)); |