PHP - Problem With Order By
Hello,
Am trying to get my records in ascending order from the database using 'ORDER BY' but they come randomly. What might be the problem? Similar TutorialsI need to add ORDER BY name ASC to this code Code: [Select] foreach($db->query("SELECT * FROM company_subcategory WHERE category_id = ".(int) $category_id) as $row) { $r[] = new CompanySubCategory($row['subcategory_id'], $row);} Tried to do it like this, but it doesn't work Code: [Select] foreach($db->query("SELECT * FROM company_subcategory WHERE category_id = ".(int) $category_id ORDER BY name ASC) as $row) { $r[] = new CompanySubCategory($row['subcategory_id'], $row);} Any help much appreciated Thanks in advance Simple for you, but I am very new to just messing around with mysql functions.
I have 1 table that tracks both the item id and the amount of views the item has.
The id column is called gId, and the views column is called gplays.
All I am trying to do is get it to show a list of the latest 100 items, but sort them as most viewed.
I've looked at online tutorials to googling the function, but can't find anything that works.
Here's my current code:
$results = $db->cachegetall(300, "SELECT gId id, gName name, gDescription descr, gThumb thumb, gplays plays FROM games ORDER BY gId DESC LIMIT 100");that just shows the latest 100. When I try ORDER BY gId DESC, gplays DESC LIMIT 100");I get nothing different. If I do ORDER BY gplays DESC LIMIT 100");I get the 100 results, but they are from all items, and I want to only get it from the latest 100 items. Can someone help me? I really have no idea what these functions are doing, other than the very basic tutorials I've read on the order by function.
Hi everyone. I'm very new into self learning programming. Presently I'm trying to develop a simple basic Robot that would only Place a Market Order every seconds and it will cancel the Order every followed seconds. Using the following library: It would place Trade Order at a ( Price = ex.com api * Binance api Aggregate Trades Price) I have already wrote the api to call for xe.com exchange rate with php <?php $auth = base64_encode("username:password"); $context = stream_context_create([ "http" => [ "header" => "Authorization: Basic $auth" ] ]); $homepage = file_get_contents("https://xecdapi.xe.com/v1/convert_from?to=NGN&amount=1.195", false, $context ); $json = json_decode($homepage, TRUE); foreach ($json as $k=>$to){ echo $k; // etc }; ?> And also for the Binance Aggregate Price in JavaScript
<script> var burl = "https://api3.binance.com"; var query = '/api/v3/aggTrades'; query += '?symbol=BTCUSDT'; var url = burl + query; var ourRequest = new XMLHttpRequest(); ourRequest.open('GET',url,true); ourRequest.onload = function(){ console.log(ourRequest.responseText); } ourRequest.send(); </script>
My problem is how to handle these two api responds and also the functions to use them to place a trade and cancel it. the interface explains everything Code: [Select] #page1.html <html> <head> </head> <body> <table border='0' width='50%' cellspacing='0' cellpadding='0' > <form name=form1 method=post action="page2.php"> <?PHP $postData[] = array(); $postData[0] = '9'; $postData[1] = '8'; $postData[2] = '7'; $postData[3] = '6'; ?> <tr> <td><b>Choose your order</b></td> <td> </td> <td> <input type=checkbox name=scripts[] value='<?PHP $postData[0]; ?>'>pasta <br> <input type=checkbox name=scripts[] value='<?PHP $postData[1]; ?>'>burger <br> <input type=checkbox name=scripts[] value='<?PHP $postData[2]; ?>'>fries <br> <input type=checkbox name=scripts[] value='<?PHP $postData[3]; ?>'>chili dog <br> <br> </td> </tr> <tr><td align=center > <input type=submit value=Submit> <input type=reset value=Reset></td></tr> </form> </table> </body> </html> Code: [Select] #page2.php <?PHP if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (isset($_POST['scripts'])) { $cb = $_POST['scripts']; $numRows = count($cb); print "you have chosen the following order numbers:"; for($i=0; $i<$numRows; $i++){ print $cb[$i] . "<br>"; } } else{ print "you have'nt checked anything!"; } } ?> What do? Hello all, I have used the phpfreaks custom order list script to create, well, a custom order list, but for some reason the Delete section of the code is not reassigning the numbers correctly after an item is deleted. It deletes the record okay, but if I have: 1 2 3 4 and delete 3, then 4 should become 3 but 4 stays as 4 until it moves two places and then it becomes 3. I am sure its related to part of this code, but please let me know if you have any ideas. Cheers Pockitz // delete row from table $sql = "DELETE FROM images WHERE imgsequenceid = '$seqid'"; $result = mysql_query($sql) or die(mysql_error()); if($result){ echo "Image $seqid successfully deleted from $id"; }else{ echo "ERROR"; } // select the info, ordering by sequenceid $sql = "SELECT imgsequenceid, imgid FROM images ORDER BY imgsequenceid"; $result = mysql_query($sql) or die(mysql_error()); // initialize a counter for rewriting sequenceid $seqid = 1; // while there is info to be fetched... while ($r = mysql_fetch_assoc($result)) { $imgid = $r['imgid']; // update the sequenceid number to the one in the next number $sql = "UPDATE images SET imgsequenceid = '$seqid' WHERE imgid = '$imgid'"; $update = mysql_query($sql) or die(mysql_error()); // inc to next avail number $seqid++; } // end while } // end if del I've got. I need to make 0, which displays as POA appear at the ned of the list not at the begining, I currently just use order by price asc and 0 is at the beginning, i need to make 0 at the end Hi there, just registered and in need of help, this looks a good place to start! I'm a php beginner so please bear with me I have a mysql database which holds 3 pieces of info id: match: 1: I'm trying to sort the results using ORDER BY match ASC but for some reason it's just not for having it... Can't work out if it's an error with my php code or my table. I can order by "ID" no problem but I when I try ordering alphabetically by "match" it won't. my code is: Code: [Select] mysql_connect("***.***.***") or die(mysql_error()); mysql_select_db("database") or die(mysql_error()); $query = "SELECT * FROM employees WHERE flag = 'tv' ORDER BY match ASC"; $result = mysql_query($query) or die ("Query failed"); $numrows = (mysql_num_rows ($result)); // loop to create rows if($numrows >0){ echo "<table width = 100% border = '0' cellspacing = '2' cellpadding = '0' >"; // loop to create columns $position = 1; while ($row = mysql_fetch_array($result)){ if($position == 1){echo "<tr>";} echo " <td align = 'center'><a href=\"http://www.website.eu/sport-stream/1/{$row['id']}.html\" target=_blank>{$row['match']} <br> <img src=\"{$row['8']}\" width=\"100\" height=\"70\" /> </a> </td> "; if($position == 4){echo "</tr> "; $position = 1;}else{ $position++;} }//while $end = ""; if($position != 1){ for($z=(4-$position); $z>0 ; $z--){ $end .= "<td></td>"; } $end .= "</tr>"; } echo $end."</table> "; }//if And here's a cap of my database: any help for a php n00b would be greatly appreciated! Hello, I have classes in a database with no set UNIX date, just the day like Wednesday and in two other columns the start and end dates. I want to be able to order by the day first and then by end_time but php orders the day column by spelling and not the day it holds in chronological order. Is there anyway to change the query to order the day column as a date? See the query below? Code: [Select] $query = "SELECT * FROM zumba_timetable WHERE end_time>'$current_time' ORDER BY day, end_time ASC LIMIT 0,1"; Currently i have a query which at the end has this Code: [Select] order by (value/counter) desc"); which works fine, however i was wondering, if in the case that 2 rows have the same, is it possible to set a second value to order by? I got this code from a previous thread: Code: [Select] mysql_query("SET @rows = 0;"); $res = mysql_query("SELECT @rows:=@rows+1 AS view_rank,COUNT(id) AS views, credit_members_id FROM vtp_tracking GROUP BY credit_members_id ORDER BY views DESC"); $n = array(1 => 'st', 2 => 'nd', 3 => 'rd'); while($row = mysql_fetch_row($res)) { if ( $row[2] != $members_id ) continue; if ( substr($row[0], -1) < 4 ) { $row[0] .= $n[$row[0]]; } else { $row[0] .= 'th'; } echo ' You are in ' . $row[0] . ' place with ' . number_format($row[1]) . ' views.'; break; } Everything seems ok except it orders by the "credit_members_id" and not "views" as entered. Can someone explain why, and how to fix this? Hello, I have a little thing I am making, and it is a Toplist. People can vote for a user, and then there vote will go up. But people can only vote once per day on one IP address. I am having a problem ordering my front page by votes though. Here is my code for it to load the votes, and to display the user's on the list. <?php include 'vote.php' $list_q = mysql_query("SELECT * FROM toplist WHERE premium='1' && activated='1' && ban='0' && staff='0' ORDER BY '$voteAmount'") or die (mysql_error()); while($list_f = mysql_fetch_assoc($list_q)) { list ($error, $message, $voteAmount) = voteAmount(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, $list_f['id']); ?> <tbody style="" id="cat_1_e"> <!-- start: forumbit_depth2_forum --> <tr> <td class="trow2" align="center" valign="middle" width="1"></td> <td class="trow2" valign="middle"> <strong><a href="server.php?view=details&id=<?php echo $list_f['id'];?>"><?php echo capitalizeFirstCharacter($list_f['servername']);?></a></strong><div class="smalltext"><?php echo $list_f['shortdescription'];?></div> </td> <td class='trow1' valign='middle' align='left' style='white-space: nowrap'><span class='smalltext'><?php echo $list_f['revision'];?></span></td> <td class="trow2" valign="middle" align="right" style="white-space: nowrap"><font size="4px"><?php echo $voteAmount;?> Votes</font></td> </tr> <!-- end: forumbit_depth2_forum --> </tbody> <?php } ?> And here is the code to my vote.php file that it loads all of the data from. <?php function install($host, $user, $pass, $db) { $c = @mysql_connect($host, $user, $pass); if(mysql_select_db($db, $c)) { mysql_query('CREATE TABLE `'.$db.'`.`votes` ( `id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, `ip` VARCHAR(50) NOT NULL, `serverId` INT(50) UNSIGNED NOT NULL, `date` DATETIME NOT NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB;'); return true; } else { return false; } } function voteAmount($host, $user, $pass, $db, $serverId) { $c = @mysql_connect($host, $user, $pass); if($c) { if(mysql_select_db($db, $c)) { if($getVotes = mysql_query('SELECT * FROM `'. $db .'`.`votes` WHERE serverId='. $serverId)) { if(mysql_num_rows($getVotes) >= 1) { $getVoteQ = mysql_query('SELECT COUNT(id) AS total FROM `'. $db .'`.`votes` WHERE serverId='. $serverId); $vote = mysql_fetch_assoc($getVoteQ); return array(0, "", $vote['total']); } else { return array(0, "", 0); } } else { if(install($host, $user, $pass, $db)) { return array(1, "The vote script has successfully been installed.<br>Please reload the page.", 0, 0); } else { return array(1, "Could not connect to DB.", 0); } } } else { return array(1, "Error connecting to DB.", 0); } } else { if(install($host, $user, $pass, $db)) { return array(1, "The vote script has successfully been installed.<br>Please reload the page.", 0, 0); } else { return array(1, "Could not connect to DB.", 0); } } } // list ($error, $message, $voteAmount) = voteAmount('HOST', 'USER', 'PASS', 'DB', $_SERVER['REMOTE_ADDR'], SERVER_ID); function votedToday($host, $user, $pass, $db, $hours, $ip, $serverId) { $c = @mysql_connect($host, $user, $pass); if($c) { if(mysql_select_db($db, $c)) { if($getVotes = mysql_query('SELECT * FROM `'. $db .'`.`votes` WHERE ip="'. $ip .'"')) { if(mysql_num_rows($getVotes) >= 1) { $dateQ = mysql_query('SELECT MAX(date) AS lastVoteDate FROM `'. $db .'`.`votes` WHERE ip="'. $ip .'"') or die(mysql_error()); $getDate = mysql_fetch_assoc($dateQ); $diffrence = time() - strtotime($getDate['lastVoteDate']); if (($diffrence / 60 / 60) >= $hours) { mysql_query('INSERT INTO `'. $db .'`.`votes` (`ip`, `serverId`, `date`) VALUES ("'. $ip .'", '. $serverId .', NOW())') or die(mysql_error()); return array(0, "Your vote has been added."); } else { return array(1, "You can only vote every ". $hours ." hours. So far ". number_format(($diffrence / 60 / 60), 2) ." hours have past."); } } else { mysql_query('INSERT INTO `'. $db .'`.`votes` (`ip`, `serverId`, `date`) VALUES ("'. $ip .'", '. $serverId .', NOW())') or die(mysql_error()); return array(0, "Your vote has been added."); } } else { if(install($host, $user, $pass, $db)) { return array(1, "The vote script has successfully been installed.<br>Please reload the page."); } else { return array(1, "Could not connect to DB."); } } } else { return array(1, "Error connecting to DB."); } } else { if(install($host, $user, $pass, $db)) { return array(1, "The vote script has successfully been installed.<br>Please reload the page."); } else { return array(1, "Could not connect to DB."); } } } // list ($error, $message) = votedToday('HOST', 'USER', 'PASS', 'DB', HOURS, $_SERVER['REMOTE_ADDR'], SERVER_ID); ?> Once again, I am trying to make it so the list is ordered by how many votes that server has. Here is an example of the votes database. Code: [Select] CREATE TABLE IF NOT EXISTS `votes` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `ip` varchar(50) NOT NULL, `serverId` int(50) unsigned NOT NULL, `date` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ; INSERT INTO `votes` (`id`, `ip`, `serverId`, `date`) VALUES (6, '::1', 4, '2010-08-07 11:44:44'); Hi. Right I'm trying to write a little script that selects one random image from a group and displays it on the page. Here is my code... $TheCat = $data['album_name']; $GetAPicy = "SELECT photo_name, album FROM photos WHERE album = '$TheCat' ORDER BY rand LIMIT 1"; $rGetAPicy = mysql_query($GetAPicy) or die(mysql_error()); $Picy = mysql_fetch_array($rGetAPicy); With this code I get the following error Unknown column 'rand' in 'order clause' Obviously I can see the error but I dont understand where they are supposed to be placed. Can anyone help? Currently I have where the User can search for records, then the records are displayed on a page. I then have a drop down box to where the user can Order by 2 different categories to make it easier for the user to see things but for some reason it is not working. Here is my code. Oh and the error I get is mysql_num_rows(): supplied argument is not a valid MySQL result resource in <?php $qry_str="SELECT * FROM timeslip WHERE 1 "; if($_POST['Initials']) { $Initials=$_POST['Initials']; $qry_str.="and Initials='$Initials' "; } if($_POST['Identifier']) { $Identifier=$_POST['Identifier']; $qry_str.="and Identifier LIKE '%$Identifier%' "; } if($_POST['Type']) { $Type=$_POST['Type']; $qry_str.="and Type LIKE '%$Type%' "; } if($_POST['Terms']) { $Terms=$_POST['Terms']; $qry_str.="and Terms LIKE '%$Terms%' "; } if($_POST['Memo']) { $Memo=$_POST['Memo']; $qry_str.="and Memo LIKE '%$Memo%' "; } if($_POST['date1']) { $date1=$_POST['date1']; $date2=$_POST['date2']; $start=date('Y-m-d', strtotime($date1)); $end=date('Y-m-d', strtotime($date2)); $qry_str.="and Date >= '$start' and Date <= '$end' "; } if($_POST['order1'] && $_POST['order2']) { $order1=$_POST['order1']; $order2=$_POST['order2']; $qry=$_POST['qry']; $qry_str="$qry ORDER BY $order1 ASC, $order2 ASC "; } if($_POST['order1']) { $order1=$_POST['order1']; $qry=$_POST['qry']; $qry_str="$qry ORDER BY $order1 ASC"; } if($_POST['order2']) { $order2=$_POST['order2']; $qry=$_POST['qry']; $qry_str="$qry ORDER BY $order2' ASC "; } $result=mysql_query($qry_str); $count=mysql_num_rows($result); if ($count>0){ ?> <form action="" method="post"> <input type="hidden" value="<?=$qry_str?>" name="qry"/> Order Results By <select name="order1" > <OPTION value="<?=$order1?>"><?=$order1?></OPTION> <OPTION value="Identifier">Identifier</OPTION> <OPTION value="Type">Type</OPTION> <OPTION value="Terms">Terms</OPTION> <OPTION value="Date">Date</OPTION> <OPTION value="Cost">Cost</OPTION> </select> Then <select name="order2" > <OPTION value="<?=$order2?>"><?=$order2?></OPTION> <OPTION value="Identifier">Identifier</OPTION> <OPTION value="Type">Type</OPTION> <OPTION value="Terms">Terms</OPTION> <OPTION value="Date">Date</OPTION> <OPTION value="Cost">Cost</OPTION> </select> <input type="submit" name="submit"> </form> Greetings! I am really stock on this situation. 1. I have a variable $uc_order_created. 2. I have a code like this: <b><?php echo t('Due Date:'); ?></b> </td> <td width="98%"> <?php $duedate = mktime(0,0,0,date("m"),date("d")+30,date("Y")); echo "".date("F jS Y", $duedate);?> 3. How do I code if I want the result of $uc_order_created get displayed as Due Date using the code above? Or other modifications? 4. The situation now, the code is working when printing the invoice but its not based on $uc_order_created. So, every time I will edit the Order because of the change of items among others the Due Date will also update. All I want that when Order is edited the value of Due Date will still remain based on the $uc_order_created. Thank you so much in advance for your help. Hi guys, i'm having trouble with making a order form for my school assignment, i'm trying to get it so that it gets the product number from one of the tables to show in a drop down box thingy any help would be greatly appricated. the code is below: <form name="Place an Order" method="post" action="order2.php "></center> <center><p>Enter the Product ID of the product you wish to purchase <a href="product.php" target="content">(cant remember? click here)</a>: <input name="ProductID" type="select" value="$query=mysql_query("SELECT ProductID FROM Products ORDER BY ProductName ASC") or die(mysql_error()); print("<select name=\"productid\">\n"); while ($row = mysql_fetch_row($query)) { printf("<option value=\"*" selected>*</option>\n", $row[0], $row[1]); } print("</select><br>");">"</p> <p>Customer ID <a href="Customer.php" target="content">(If you are not already a customer click here)</a>: <input name="CustomerID" type="text" value="Customer ID"></p> <p>Quantity: <input name="Quantity" type="text" value="99"></p> <input name="Place Order" type="submit" value="Place Order"> </center> </form> So say I have a union sql statement like this: (SELECT id, card_id, ordered FROM Match_1 WHERE card_id='$card_id') UNION (SELECT id, card_id, ordered FROM Match_2 WHERE card_id='$card_id') UNION (SELECT id, card_id, ordered FROM Match_3 WHERE card_id='$card_id') ORDER BY ordered ASC ordered is an INT, but yet when I order the results its like this 1 11 2 11 should obviously be last but it isn't, what am I doing wrong? Hi all, I have a script that is essentially a log file of all preious versions of an article (versioning) You can see the script I am talking about in action at: http://danielrhyshardy.com/AWT/forumadmin.php What I would like to do is, instead of displaying the title of each instance (you will see there are two instances named "apple", as they are two previous versions of an article), I would like to display that title once, and then all of the instances of that title be displayed below. I hope that makes sense. Here is the code Code: [Select] <? $sql = "SELECT id,title,message,date_added FROM messages2 ORDER BY id "; $result = mysql_query($sql) or trigger_error(mysql_error(),E_USER_ERROR); while(list($id,$title,$message,$date_added)=mysql_fetch_row($result)){ echo '<div style="color:#bb0000;width:250px;text-align:center;float:left;margin-left:15px;margin-bottom:15px;padding-bottom:20px;"><b>'.$title.'<br>'.$date_added.'</b> <input id="'.$message.'" type="radio" name="admin[]" value="'.$id.'" onclick="javascript:document.form22.car.value=this.id" > </font></div>'."\n"; } ?> I would use something like Code: [Select] if ($title = "apple") { but this would obviously not work for new posts, unless I wanted to constantly update my code. I am sure there is a simple way to achieve this. Perhaps someone can tell me!? Thanks in advance Dan Hi everyone, I'm looking for a point in the right direction. I just about to start my biggest coding project yet. (A Simple PHP Order form). The client has suggested that they want a form for users to enter a reference code (from a catalog) of a product type how many items they want. It will generate a sub total. And if the total is over a certain amount discount will be given. The form will also have the regular form fields as well. e.g Name, email, address etc... Then all this will post to a email. I've created contact form scripts before. But is there any links or tutorials that could help me do this or even point me in the right direction. Thanks for all the help Barry Hi I can't get the ORDER BY to work correctly: Code: [Select] $getchallenges = safe_query("SELECT * FROM ".PREFIX."cup_challenges WHERE ladID='$laddID' AND challenger='$teamID' ORDER BY $order_date DESC"); while($gc=mysql_fetch_array($getchallenges)) { ... if($gc['finalized_date']) $order_date = "finalized_date"; elseif($gc['reply_date']) $order_date = "reply_date"; else $order_date = "new_date"; ... } Is it because of loop? echo "order = $order_date"; output: order = order = order = new_date What I'm trying to achieve is to order by the latest date, but I have 3 date columns: new_date reply_date finalized_date Is it possible to order by multiple columns where largest to smallest? |