IDs not sorting - php

I got an odd problem. Whenever I add a new entry to the database it gives it a higher id number, but somehow sees it as a lower number and puts it below the older ones.
And when sorting DESC in PHP I also get this order, does anybody know whats going wrong here?
I use $res = mysql_query("SELECT * FROM data ORDER BY 'id' DESC");to sort them, and it gives the same order as in the pic. (Not sure why i'm being downvoted here but ok..)
Pic:

Your query is:
SELECT * FROM data ORDER BY 'id' DESC
You are sorting by the string 'id', note the syntax highlighting when not within quotes. This means you get them in a random order. Remove the '. If you meant to escape the column id you should use back-ticks:
SELECT * FROM data ORDER BY `id` DESC

When you insert data on the tables, it does not mean that the new number (or the highest) always on the lowest row. It randomly inserts the record. The only way you can sort it when you retrieve the rows in by using ORDER BY clause, example
SELECT *
FROM tableName
ORDER BY ID DESC
So assume that ID is numeric. If you're ID is stored as string then you should convert it to numeric,
SELECT *
FROM tableName
ORDER BY CAST(ID AS SIGNED) DESC
UPDATE 1
It should be
$res = mysql_query("SELECT * FROM data ORDER BY `id` DESC");
not
$res = mysql_query("SELECT * FROM data ORDER BY 'id' DESC");
what you have done was you have surrounded the ID with single quote forcing the server to read it as String and not Numeric

When you are not using any ORDER BY clause, the order in PHPMyAdmin is kind of random. Indeed, new rows could take place of old ones.
I am curious how you sort DESC in PHP though.

Don't absolutely trust in GUI web interface because sometimes (not always) it bugs with session management, however you can run SQL Queries using it.
1- To run a SQL query, click on "SQL" on the navigation bar.
2- Enter your SQL in the box provided.
SELECT *
FROM tableName
ORDER BY ID DESC
3- Click "Go".

Related

ROWNUM doesn't work; trying to grab info on specific row range in SQL query

I have a bit of code that counts the number of rows upon an SQL query and then does another query to grab information on the last four rows. I've used ROWNUM, but it doesn't work.
$newscount = $db->query("
SELECT *
FROM news
");
$counter = $newscount->rowCount();
$grabnewsmsg = $db->query("
SELECT *
FROM news
WHERE ROWNUM >= $counter-4 -- this particular part doesn't owrk
ORDER BY updateno DESC -- an A_I column
");
I've commented the specific areas I'm having problems. The A_I part is fine, since there should be a unique identifier for each row, but ROWNUM just doesn't work despite what I have read on other sites in addition to other questions/answers on SO. It returns an error column rownum does not exist.
I want to get information on solely the last four rows ($query->rowCount()-4), but I can't select via a certain updateno threshhold. If a user deletes a row, the A_I column cannot be appropriately used to determine the row number.
Additionally, I've tried the below:
$grabnewsmsg = $db->query("
SELECT *
FROM news
ORDER BY updateno DESC
LIMIT 0,4
");
And while this gives the desired results, I'm still not sure why ROWNUM doesn't work.
You need to understand the meaning of that AUTO_INC thingy. It is called an unique identifier, and for a reason. "Unique" means no other row should have the same identifier ever.
Yet it has absolutely nothing to do with whatever enumeration. So -
I have an autoincrementing column titled 'updateno' which corresponds to the number of the row.
this is what you are doing wrong.
As a matter of fact, you don't need such a field at all. If you wnat to enumerate your fields - do in on the fly. If you want an identifier - use a conventional name for this - "id"
While for the whatever "rownum" feature you need another mysql operator, namely LIMIT

I need to select newest rows from a MySQL database, but verify that I am also returning a row with a given ID

I'm new to this, sorry if the title is confusing. I am building a simple php/mysql gallery of sorts. It will show the newest 25 entries when a user first goes to it, and also allows off-site linking to individual items in the list. If the URL contains an ID, javascript will scroll to it. But if there are 25+ entries, it's possible that my query will fetch the newest results, but omit an older entry that happens to be in the URL as an ID.
That means I need to do something like this...
SELECT * FROM `submissions` WHERE uid='$sid'
But after that has successfully found the submission with the special ID, also do
SELECT * FROM `submissions` ORDER BY `id` DESC LIMIT 0, 25`
So that I can populate the rest of the gallery.
I could query that database twice, but I am assuming there's some nifty way to avoid that. MySQL is also ordering everything (based on newest, views, and other vars) and using two queries would break that.
You could limit across a UNION like this:
(SELECT * FROM submissions WHERE uid = '$uid')
UNION
(SELECT * FROM submissions WHERE uid <> '$uid' ORDER BY `id` LIMIT 25)
LIMIT 25
Note LIMIT is listed twice as in the case that the first query returns a result, we would have 26 results in the union set. This will also place the "searched for" item first in the returned sort result set (with the other 24 results displayed in sort order). If this is not desirable, you could place an ORDER BY across the union, but your searched for result would be truncated if it happened to be the 26th record.
If you need 25 rows with all of them being sorted, my guess is that you would need to do the two query approach (limiting second query to either 24 or 25 records depending on whether the first query matched), and then simply insert the uid-matched result into the sorted records in the appropriate place before display.
I think the better solution is:
SELECT *
FROM `submissions`
order by (case when usid = $sid then 0 else 1 end),
id desc
limit 25
I don't think the union is guaranteed to return results in the order of the union (there is no guarantee in the standard or in other databases).

How to select from last to first row in mysql

Whenever a query like
"select * from table where userid=xx" is done, the mysql fetches these values from
first row to last row of table.
But I want to select from last to first so that recently updated values are displayed first in the results.
I cannot do "select * from table where userid=xx order by time DESC" because there is no time column in table.
I just want recently updated items in the table displayed first.
$result= mysql_query("SELECT
(SELECT column FROM table WHERE [condition] ORDER BY column LIMIT 1) as 'first',
(SELECT column FROM table WHERE [condition] ORDER BY column DESC LIMIT 1) as 'last'");
$row=mysql_fetch_array($result);
echo $row['first'];
echo $row['last'];
If you have any auto-incrementing field you could sort by that desc.
You must provide a column to order by in order to guarantee results. So you will have to either change your table structure or make a decision on what to order by.
A hack would be to pull in the data in the order presented into an array, then start popping off the bottom of that array.
You either have to have a timestamp, or autoincrement id, or some other column that you want to sort by.
Just because you get rows in a certain order from a database when not using an ORDER BY clause, does not mean that they are guaranteed to be returned in that order. It also doesn't imply any order in the result set. You need a definitive field that you can use to ORDER BY, or you cannot do what you are wanting to do.
Some hack you can do for that if you don't have columns you can rely on:
SELECT * FROM (SELECT *,(#x:=#x+1) default_ordering FROM `table_name`, (SELECT #x:=0) t2) any_name ORDER BY default_ordering DESC

Select Statement By ORDER

I have a column which holds status of applications - (New/Approved/Declined/Pending)
The column name is status. Now how do I order the select statement to order status so that 'New' applications come to the top of the display.
I tried this (SELECT * FROM applications ORDER BY status where status ='New')
This does not work, it is giving me error message.
Given status values "archived", "new" and "old" (for which neither ASC or DESC are working) and you want to retrieve all rows, "new" ones first, use this:
SELECT * FROM `applications`
ORDER BY IF(`status` = "new", 0, 1)
Try this:
SELECT * FROM applications ORDER BY status ASC;
If all you have is 'New' and 'Old', then this will result in 'New' first.
If you ONLY want New orders then you don't need an ORDER BY:
SELECT * FROM applications WHERE `status` = 'New';
If there are all kinds of values, like New/Approved/Declined/Pending and you just want to make sure 'New' is at the top you can do this
SELECT * FROM applications ORDER BY `status`, FIELD(`status`,'New');
What if you want 'New' first, then 'Approved', then you don't care what?
SELECT * FROM applications ORDER BY `status`, FIELD(`status`,'New','Approved');
(ASC and DESC have no effect after FIELD, but DESC after status will put your favorite values at the bottom rather than the top)
What about reversing their order but keeping them at the top? Either change their order in the FIELD() function or see below.
Finally, contrary to the previous suggestion, this does not really work:
SELECT * FROM applications ORDER BY FIELD(`status`,'New','Approved'),`status`;
To fix it, you need DESC after FIELD, but it gives you your values ordered in reverse (i.e. 'Approved' first, then 'New', then the rest):
SELECT * FROM applications ORDER BY FIELD(`status`,'New','Approved') DESC,`status`;
I think I spent too much time on this answer. Hmmm.
ugly but
(SELECT * FROM applications where status ='New')
union all
(SELECT * FROM applications where status !='New')
If you want to use this for something serious, replace the status column with a foreign key and add another table for the textual representations of your status_ids.
Then you can sort using
SELECT * FROM applications ORDER BY status_id
Try to avoid using reserved names for columns. It is possible to use them (with backticks), but can easily lead to problems if you don't take care.

Order mysql results without identifier

Usually I would have a table field called ID on auto increment. That way I could order using this field etc.
However I have no control over the structure of a table, and wondered how to get the results in reverse order to default.
I'm currently using
$q = mysql_query("SELECT * FROM ServerChat LIMIT 15");
However like I said there is no field I can order on, so is there a way to tell mysql to reverse the order it gets the results? I.e last row to first row instead of the default.
MySQL supports ordering by ordinal column position:
SELECT * FROM ServerChat ORDER BY 1 DESC LIMIT 15
But IIRC this usage of ORDER BY is deprecated in the SQL standard. Don't be surprised if some RDBMS vendors discontinue support for it (eventually).
In general, it's better to know your table structure.
No. Without a field to order there is no way
You are in fact getting your results in what is known as "table order", which may look like it's in the order that data was added to the table but that order is not stable. There are a number of operations that can change the order you are receiving results without changing the data in the table itself.
To reproduce the sort of order you are seeing I'd suggest adding a column to your table of type ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP. This will give you a column to specifically order on and therefore reverse that order. You should probably add an index on that column as well if this operation is a frequent one.
According to this article, SQL-92 allows the user to query table structure information from a "well known" view or table called INFORMATION_SCHEMA. SQL-92 is supported by MySQL 5.0 and up.
Example/Excerpt:
SELECT table_name, column_name, is_nullable, data_type, character_maximum_length
FROM INFORMATION_SCHEMA.Columns
WHERE table_name = 'employees'
So you could use the list of column names to allow the user to select which column it's ordered by, then use this SO answer to figure out how to build the dynamic SQL so you execute the query correctly.
I've not tried it with MySQL, but the method certainly makes sense to me.
Your table must have some unique index specified. It doesn't have to be named ID but it's typically required and likely what's determining the order returned currently. What is it? Whatever it is, it's my understanding that you should be able to do an ORDER BY ... DESC (or if that doesn't work, ASC) like this example with the unique identifier hash:
$q = mysql_query("SELECT * FROM ServerChat ORDER BY `hash` DESC LIMIT 15");

Categories