PHP - Union And Order By
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? Similar Tutorialsi have this query and i'm trying to order all of the results by `created` ascending. I've tried putting the later query before the first but the single row from the first query(the way it is right now) gets stuck as the last row in the results. How can i order the results of both queries? Code: [Select] ( SELECT * FROM Account_activity WHERE DATE( created ) < '2011-08-01' AND username = '40' ORDER BY created DESC LIMIT 1 ) UNION ( SELECT * FROM Account_activity WHERE MONTH( created ) = '08' AND YEAR( created ) = '2011' AND username = '40' ORDER BY created ASC ) This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=332593.0 The following union query is supposed to return the total number of alerts and the total number of messages, however a dump of the returned array shows only the alerts(num_alerts). $sql = "SELECT COUNT(a.a_aid) as num_alerts FROM ".Asf_Db::$prefix."alerts a UNION SELECT COUNT(m.m_mid) as num_messages FROM ".Asf_Db::$prefix."messages m"; $sth = Asf_Core::$db->prepare($sql); $sth->execute() or die(Asf_Core::$db->error($sth, $sql)); $results = $sth->fetch(PDO::FETCH_ASSOC); dump($results); anyone see where im going wrong? Here's what i've been attempting to do . a. I have a table "travelexpense" in 2 DBs. All columns are identical. b. Based on a set of parameters, a user can have a record in this table in one or both of the databases. c. When i want to output all the entries pertaining to that user in both these tables, I use Select Union. So far so good. d. However, the query references customers pertaining to those expenses . The customer table is present in both databases but is populated with different records. e. Now when the SELECT UNION runs, it picks up only the customer in the first database and not the second, even if there is an entry pertaining only to the second database. f. Odlly though the other data - that is the expenses themselves are selected correctly. Its only the customers entries that are wrong Code snippet below Code: [Select] $sqlZ= " SELECT * FROM $dbname2.`Travelexpense` WHERE Userid='$user' && MONTH(`Enddate`)=$month && YEAR(`Enddate`)=$year UNION select * from $dbname3.`Travelexpense` WHERE Userid='$user' && MONTH(`Enddate`)=$month && YEAR(`Enddate`)=$year "; $resultZ = mysql_query($sqlZ) or die (mysql_error()); $numofrows = mysql_num_rows($resultZ); for($i = 0; $i < $numofrows; $i++) { $myrowZ = mysql_fetch_array($resultZ); $coid = $myrowZ["CID"]; $s1 = "SELECT * FROM $dbname2.`Customers` WHERE `CID` = $coid UNION select * from $dbname3.`Customers` WHERE `CID` = $coid"; $result1 = mysql_query($s1); $myrow2 = mysql_fetch_array($result1); $Name=$myrow2["Company"]; //here's the problem . If say $coid = 150 , then it will look only at record 150 in Table Customers in dbname2 and NOT in Table Customers in dbname3 even if only dbname3 has a relevant entry. blah blah } Am i using UNION incorrectly esp in the query $s1? Appreciate any help . Thanks ! Swati The queries merge ok and results are correct except I get a notice: "Notice: Use of undefined constant UNION - assumed 'UNION' in...."
But is UNION a constant or is the context wrong?
$query = $query1." ".UNION." ".$query2; $result = mysqli_query($dbcon, $query) or die('Error getting data'); $num_rows = mysqli_num_rows($result); $sql=mysql_query("SELECT * FROM `buds` WHERE `level`<='$user_level' UNION SELECT * FROM `buds`, `unlocked_buds` WHERE buds.`id` = unlocked_buds.`bud_id` ORDER BY buds.`id` ASC") or die("A MySQL error has occurred.<br />Your Query: " . $sql . "<br /> Error: (" . mysql_errno() . ") " . mysql_error()); I have been trying to learn about UNION select statements. I ran the query above and got this response: Quote Error: (1222) The used SELECT statements have a different number of columns I think I know what the problem is, but not sure how to fix it. There is two columns, one is "buds" which holds the flowers seeds info. The seconds is "unlocked_buds" which just links the "id" from buds to "user_id" to the user table. Both buds and unlocked_buds are both 8 columns. What do I need to learn? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=308424.0 Hi I'm trying to find the max value in 3 columns, new_date, reply_date and finalized_date in my table: Code: [Select] $test = safe_query("SELECT MAX(new_date) FROM (SELECT new_date AS new_date FROM ".PREFIX."cup_challenges UNION SELECT reply_date FROM ".PREFIX."cup_challenges UNION SELECT finalized_date FROM ".PREFIX."cup_challenges) AS maxval"); Did some research and have no idea what is wrong/if the above is correct? The page breaks below this code. This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=321649.0 This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=306274.0 Is there a cleaner way to do this? $query = "SELECT branches.Language FROM eua_users, branches WHERE eua_users.AssignedBranch = branches.country" ; include("dbconnectlocal.php") ; $result = mysql_query($query) ; $row = mysql_fetch_object($result) ; $usrlang = $row->Language ; $query = "SELECT UserName, Email FROM eua_users WHERE UserName = '$user'" ; include("dbconnectlocal.php") ; $result = mysql_query($query) or die(mysql_error()); $row = mysql_fetch_object($result) ; $branchmail = $row->Email ; $query = "SELECT $usrlang FROM autoreplies WHERE ReplyID = '0'" ; include("dbconnectlocal.php") ; $result = mysql_query($query) or die(mysql_error()) ; $row = mysql_fetch_object($result) ; $message = $row->$usrlang ; $query = "SELECT $usrlang FROM autoreplies WHERE ReplyID = '1'" ; include("dbconnectlocal.php") ; $result = mysql_query($query) or die(mysql_error()) ; $row = mysql_fetch_object($result) ; $url = $row->$usrlang ; $query = "SELECT $usrlang FROM autoreplies WHERE ReplyID = '2'" ; include("dbconnectlocal.php") ; $result = mysql_query($query) or die(mysql_error()) ; $row = mysql_fetch_object($result) ; $subject = $row->$usrlang ;
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. 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 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? 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? 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"; I'm just trying to see if the order of my logic is correct or if there's something I can do differently. I'm also curious to know at what point I should get the 2 passwords that exists in the database for the user. These are two different passwords. Code: [Select] function login_submit() { $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean'); $this->form_validation->set_rules('remember', 'Remember me', 'integer'); $user_id = $this->users->get_user_id_by_username($this->input->post('username')); if ($user_id !== 0) { if ($this->kow_auth->is_max_login_attempts_exceeded($user_id)) { echo json_encode(array('error' => 'yes', 'message' => 'Your account is currently locked, we appologize for the inconvienence. You must wait 10 minutes before you can login again!')); } else { $user_status = $this->users->get_user_status($user_id); if ($user_status == 1) { echo json_encode(array('error' => 'yes', 'message' => 'Sorry you must verify your account before logging in!')); } elseif ($user_status == 3) { echo json_encode(array('error' => 'yes', 'message' => 'Your account has been suspended!')); } elseif ($user_status == 4) { echo json_encode(array('error' => 'yes', 'message' => 'Your account is currently banned!')); } elseif ($user_status == 5) { echo json_encode(array('error' => 'yes', 'message' => 'Your account has been deleted!')); } else { if ($this->form_validation->run()) { if ($this->kow_auth->login($this->form_validation->set_value('username'), $this->form_validation->set_value('password'), $this->form_validation->set_value('remember'))) { redirect(''); } else { echo json_encode(array('error' => 'yes', 'message' => 'Incorrect username and password combination!')); } } } } } else { echo json_encode(array('error' => 'yes', 'message' => 'Incorrect username and password combination!')); } } 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 |