How can I order html table with data from database? [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I've got a question regarding a html table and data from a database.
I managed to create a html table, which fetches data from a mysql database. So far it works fine. I am using auto increment within the database.
Unfortunately the html table is going from up to down. So the first entry has ID 1, while the last entry has a higher number. I want to change that so that the entry with the higher ID is displayed on top.
Is there any possibility to do that without Javascript or buttons? I didn't found a solution yet.

You can use ORDER BY change the list to start from higher number to the lower.
The ORDER BY keyword is used to sort the result-set by one or more columns, it sorts the result-set in ascending by default if you want it in descending (your case) you can use the DESC keyword.
So update your SQL query as follow.
SELECT *
FROM table_name
ORDER BY COLUMN_NAME_TO_SORT DESC
http://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html
You can also use PHP's usort() function to sort the result-set fetched from database.
Sample code to sort the array by specific column using usort()
usort($finalarray, function($a, $b) {
return $finalarray['COLUMN_NAME_TO_SORT'] - $finalarray['COLUMN_NAME_TO_SORT'];
});
// Assuming $finalarray is a result-set from database and it's an array.
Reference: http://php.net/manual/en/function.usort.php
ORDER BY in SQL directly is preferred and better option to sort the result by higher
ID to lower.

Yes you can do that in a MySQL statement:
SELECT *
FROM table
ORDER BY ID DESC
It's the last line you need to add. With ORDER BY you can set the order in which the SELECT results are presented. The order can be DESC (descending), or ASC (ascending). You can order on multiple columns, seperated by comma's, it will then first sort on the first column, then on the second, etc.

Related

How to order two tables with no relationship and different columns, by a single column that they share (date) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I've got two tables in a MYSQL database. One Is a for blog posts and one is for videos. All the columns in each of them are different except for one which is the date they were created.
On the main page of my website I want to show most recent posts, whether that be a video or a blog post. So I want to order them based on their shared date column. Is this something I can do in MYSQL or would I have to pull all the data into php and then order it using my own function.
I've looked up other answers but they all seem to be cases where the tables have no relationship but share the same columns.
For table to be used in the same result set as you are suggesting, you would need a UNION; but UNIONs require all union-ed queries to have the same columns in their results. If the only field in common you have is "date"; the best you could probably do is something like.
SELECT `date` AS postDate, 'Video' AS postType
, someVideoField, null as someBlogField
FROM video_table
UNION
SELECT `date` AS postDate, 'Blog' AS postType
, null as someVideoField, someBlogField
FROM blog_table
ORDER BY postDate
;
Note: The latter aliases are not actually needed, I just tend to do that for clarity as to which field is expected to map to which. Also, the null as someBlogField portion may need tweaked to insure the result field is a type that can accept the real values from the latter half of the union; the first half determines field types.
If you end up using two queries it's easy enough to put them together in your script.
while ($row = $blogQuery->fetch()) {
$results[$row['date']]['blog'] = $row;
}
while ($row = $videoQuery->fetch()) {
$results[$row['date']]['video'] = $row;
}
If you ordered by date in your select queries, this will already be mostly in the right order, except for dates where only the video query has rows (or whichever one you fetched second). You can ksort($results) to fix the order for any of those.

Random like order with mysql and PHP [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I use PHP and Mysql. I have a table that looks kind of like this:
id title
----------
1 my title
2 another title
3 The last title
Now I want to select them with a random like order.
I will need to use LIMIT because of the query size.
The random like order should always be the same random order every time.
Example result, every time
3 The last title
1 my title
2 another title
Do another query run:
3 The last title
1 my title
2 another title
The same random like result appear.
Possible solutions
Add a real random number stored as a new column generated by insert.
Some fancy SELECT query that does some magic.
Something else?
Why I want this is that I insert products, first from one site, then from another. In the result I want to present them as a mix.
It's not really random at all, but then again your request wouldn't work with random numbers. You want some sort of a hash of each record to use in the order by. You can probably find something better, but as a simple example you could use:
SELECT * FROM my_table ORDER BY MOD(id, 2);
Which you can see working here:
http://sqlfiddle.com/#!9/269a4/1/0
Use ORDER BY RAND().So your query should be :
select * from <tablename> where <cond> then ORDER BY RAND() limit <startlimit>, <end limit>

How to echo fetched array data from a mysql database in custom order? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have been trying to print out data from a database table in custom order like for example..
I have a table and that have alot rows and have one column as listing_type which have values like Gold,Premium,Silver,Free etc for each row..! so how I would be able to print the data from fetched array in order like at first it should echo all Gold and then Premium and then Silver and then Free etc like..!
Any help would be appreciated..Thanks waiting for your reply.!
Use an ORDER BY clause in your MySQL query like this:
SELECT *
FROM `table`
ORDER BY FIELD(`listing_type`, 'Gold', 'Premium', 'Silver', 'Free')
The MySQL function FIELD() returns the position of str in the given strings. With this, you can create a custom order to sort your results on.
In Mysql query you can easily order results by using field() function,so returned results will be ordered in way where listing_type is gold first then premium then silver results then free
select *
from your_table
order by field(listing_type,'Gold','premium','Silver','Free' )

How to store a random SQL query by its ID? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
$randWord = mysql_query("SELECT * FROM words ORDER BY RAND() LIMIT 1");
After I call a random row from my table (which includes a word, its definition, and an id column) I want to store that word and definition so I can edit it if another button is pressed. From what I've seen online the common solution is to store it by its id. How do I store a random SQL query by its id?
Here's an example of where the pro tip
Never use SELECT * in software, instead give the names of the
columns you want.
would have helped you. If your words table has an id column, store that value.
RAND() and fetching by * is strongly not recommended because of it's bad performance.
Suggested example:
$total = mysql_result(mysql_query('SELECT COUNT(*) FROM words'), 0);
$randWord = mysql_fetch_array(mysql_query('SELECT wid, word, definition FROM words LIMIT '.rand(0, $total - 1).', 1'), 0);
Where mysql_result obtains the total number of records, mysql_fetch_array turns the result into an array. rand(0, $total - 1) generates a random number between available records, and then satisfy the [LIMIT start, limit] statement in the query.
You may build up your own DB class to reduce the code redundancy.
For your question, you should create a field as a primary key (or unique identifier). Like the 'wid' field I suggested above. Then you can output it as the value of a button and so on.

Sql execution order [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am confusing with simple query:
SELECT * FROM table_name WHERE name = 'stack';
My question is this which part first execute:
SELECT * FROM table_name
OR
WHERE name = 'stack'
First select all record from table then filter with WHERE condition or
first filter records then SELECT?
For more details about question please see this link:
WHERE condition issue in SQL
Thanks
The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. Note that the actual physical execution of the statement is determined by the query processor and the order may vary from this list.
FROM
ON
JOIN
WHERE
GROUP BY
WITH CUBE or WITH ROLLUP
HAVING
SELECT
DISTINCT
ORDER BY
TOP
It selects all the records first from the table and then filter in sequence according to the condition or conditions specified.

Categories