How to order query results with multiple datetime? - php

I do want to sort my results from different datetimes, like this ("SELECT * FROM table ORDER BY datetime_1 and datetime_2 and datetime3 DESC");
is that possible ??

If you use SQL to get your posts, you can try this:
SELECT * FROM your_posts_table ORDER BY your_date_field DESC
In some situations, you may just add
ORDER BY your_date_field DESC
after your SQL.
if you using ORM, you have to look at the document.

your overwriting while($users->results() as $users) { $users variable
so you have to do something like this
while($users->results() as $users_data) {
echo $user_data->name;
}

Related

PHP and Mysql || 'or' syntax?

In mysql I have something like:
$currentname = mysql_query("SELECT * FROM posts LIMIT $start, 5 WHERE ");
How can i do something like this below that works:
$currentname = mysql_query("SELECT * FROM posts LIMIT $start, 5 WHERE `title` LIKE '%{Hello world}%' || Where `text` LIKE '%{Hello World}%'");
Something like above that will actually work.
Try this:
$queryResult = mysql_query("SELECT * FROM posts WHERE `title` LIKE '%{Hello world}%' OR `text` LIKE '%{Hello World}% LIMIT $start, 5'");
$currentName = mysql_fetch_assoc($queryResult);
if you expect many results...
while($currentName = mysql_fetch_assoc($queryResult)) {
//your code here...
}
Replace || with OR and remove the extra WHERE that comes after it. In SQL, || is OR and && is AND. You can read more here.
Note: Please take time to read manuals, it absolutely helps.
You can use OR in MySql, and it is likely very suitable for most situations.
OR however has a slight disadvantage performance wise as for each OR query the whole query is ran again. I am no MySql performance guru, but it would seem UNION is better optimized. So in general, and at lest with more OR statements you should use a UNION like this:
SELECT your_union_result.* FROM
(
SELECT * FROM posts WHERE `title` LIKE '%{Hello world}%'
UNION
SELECT * FROM posts WHERE `text` LIKE '%{Hello World}%'
) AS your_union_result
ORDER BY your_union_result.order_column
LIMIT $start, 5
Please note: My version has a subquery. You need it in case you want to order the result or limit the total rows. You now have a few options to fetch the actual result.
You can fetch_assoc(), fetch_array() and so on row by row. It is unclear for me what you want as the actual result. The $currentname indicates a post or user name, but a limit of $start, 5, indicates you want a list.
Go ahead and read http://php.net/manual/en/function.mysql-fetch-array.php and the other fetch functions. If you need more help, please update your question to be a bit more specific.

How to order strings format from database in PHP?

I have numbers like this: 666/2014, 01/2014, 1/2014, 02/2014, 125/2014, 06/2014 ...etc as STRING named 'n_inscription' in database.
I want to retrieve those strings In ORDER from database
I used this:
$sql_students = $bd->query("SELECT * FROM `es_student_infos`
WHERE school_year='$school_year'
ORDER BY right(n_inscription, 4) * 1,
substring_index(n_inscription, '/', 1) * 1");
I get result like this:
01/2014,
02/2014,
06/2014,
1/2014,
125/2014,
666/2014
and the result I'm looking for is like this:
01/2014,
1/2014,
02/2014,
06/2014,
125/2014,
666/2014
any suggestion please?
The best approach is probably to normalize the input so normal sorting does what you want it to do. For example, store the student number and year in two separate INTEGER columns and then ORDER BY studentNumber ASC, inscriptionYear ASC.
If that's absolutely not possible:
SELECT
*
FROM
es_student_infos
ORDER BY
CAST(RIGHT(n_inscription, 4) AS UNSIGNED) ASC,
CAST(LEFT(n_inscription, LOCATE('/', n_inscription) - 1) AS UNSIGNED) ASC
Link to fiddle demonstrating the solution: http://sqlfiddle.com/#!2/a5538/1/0
The correct way is change the type of n_inscription to date/datetime/timestamp and then use order by as default.
There's more advantages to use date fields like comparison and date calculations, so I suggest you do like this.
EDIT: Change the order by collumn to school_year and not n_inscription:
SELECT * FROM `es_student_infos`
WHERE school_year='$school_year'
ORDER school_year

How to echo MySQL results in inverse order?

$result3=mysql_query("select * from $mail");
while($row=mysql_fetch_array($result3)) {
if($row['status']!=NULL) {
echo $row['status'];
echo $row['date'];
echo $row['time'];
}
}
i want that the last field in the database should be displayed first. How to implement this?
$result3 = mysql_query("SELECT * from $mail ORDER BY `date` DESC");
Never do yourself what the database can do for you.
If, for whatever weird reason, you actually want to traverse the result set in reverse order, you'll have to use mysql_data_seek, starting at mysql_num_rows() - 1 and decrementing the pointer after each call to mysql_fetch_array.
Use an ORDER BY clause in your query so that the results come in the order you want to display them.
Without an ORDER BY, there is no guarantee about what order the data will come in, so "reversing" that doesn't make sense.
Either user an ordering in the SQL query itself using ORDER BY or put them into an array in PHP and reverse the array:
$all_rows = array();
while($row=mysql_fetch_array($result3)) {
$all_rows[] = $row;
}
$all_rows = array_reverse($all_rows);
Order your fields with the ORDER BY sql feature. So choose what field you want to order by, and order it by that field..
$result3=mysql_query("select * from $mail ORDER BY date DESC ,time DESC");
or if they have an id field:
$result3=mysql_query("select * from $mail ORDER BY id DESC");
And while you're at it, make sure that you know EXCATLY what is in $mail!
"select * from $mail order by date DESC, time DESC"

Mysql Order by Tweak

I have a database with nearly 100 fields.
DB structure is
id | comment | time
I need to fetch only 5 newest record (I can get those records using ORDER by time DESC). But while printing them I need to print the oldest of those 5 records first and proceed in reverse in a way that the newest record will be printed last.
SELECT s.* FROM (
SELECT id, comment, time FROM table1
ORDER BY time DESC
LIMIT 5 ) as s
ORDER BY s.time ASC
Ok, after fetching result set in ascending order with a limit of number of rows
you can do this to print them in reverse order (descending order)
$data= array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
$records = array_reverse($data);
OR
This could be done with mysql_data_seek
Directly taken from here
for ($i = mysql_num_rows($resultset) ā€“ 1; $i >= 0; $iā€“) {
mysql_data_seek($resultset, $i);
$row = mysql_fetch_assoc($result);
echo $row['abc'] . ' ' . $row['xyz'] . "\n";
}
You can use PHP's array_reverse() function on your result list.
http://php.net/manual/en/function.array-reverse.php
You can use also something like this:
select * from (select * from table_name where 1=1 order by time desc
limit 5) as tbl order by tbl.time;
Edit if you have a lot of accesses to this statement it would be much better to represent it as materialized view. Though there are no materialized views in mysql it is possible to simulate them (http://lists.mysql.com/mysql/207808)
Using a materialized view or a simulated materialized view will seriously outperform the suggested php approaches. Most of the mentioned ones consume to much memory anyways .
I guess you could do something along the lines of (untested):
SELECT
*
FROM (
SELECT
id, comment, time
FROM
table
ORDER BY
time DESC
LIMIT 5
)
ORDER BY
time ASC
UPDATE
Apparently, the "derived table must have its own alias" (error #1248). Other answers have already done this, so I'll jump on the bandwagon. Below you'll find the revised (and tested) query:
SELECT
derived.*
FROM (
SELECT
id, comment, time
FROM
table
ORDER BY
time DESC
LIMIT 5
) AS derived
ORDER BY
derived.time ASC
By the way, this is supported as of MySQL 4.1.

Joining 2 mysql queries

I have two tables which I need to select all rows from where the userid is $userid then sort them. I tried to use join but I couldn't even really get started on how to get it right. Can anybody point me in the right direction as to how to make these into one query?
$result1 = mysql_query("SELECT * FROM paypal_sub_info
WHERE userid='$THEuserid' ORDER BY cur_time DESC");
$result2 = mysql_query("SELECT * FROM paypal_pay_info
WHERE userid='$THEuserid' ORDER BY cur_time DESC");
while($row = mysql_fetch_array($result1)){
echo $row['txn_type'];
}
Solution:
SELECT *
FROM paypal_sub_info sub,paypal_pay_info pay
WHERE pay.userid = '$THEuserid'
AND sub.userid = '$THEuserid'
ORDER BY pay.cur_time DESC,sub.cur_time DESC
Try this:
SELECT * FROM paypal_sub_info sub, paypal_pay_info pay
WHERE pay.userid='$THEuserid' AND sub.userid='$THEuserid'
ORDER BY pay.cur_time DESC, sub.cur_time DESC
If you just want 'txn_type', you could make it a SELECT pay.txn_type AS txn_type
Use:
SELECT psi,*, ppi.*
FROM PAYPAL_SUB_INFO psi
JOIN PAYPAL_PAY_INFO ppi ON ppi.userid = psi.userid
WHERE psi.userid = $THEuserid
ORDER BY psi.cur_time DESC, ppi.cur_time DESC
I believe you want:
SELECT field1, field2, ... FROM paypal_sub_info WHERE userid='$THEuserid'
UNION
SELECT field1, field2, ... FROM paypal_pay_info WHERE userid='$THEuserid'
ORDER BY cur_time DESC
So first off consider using mysqli for for any serious project. OMG Ponies answer is how I would suggest doing it, thought you shouldn't have to specify the alias.wildcard fields separately in the select clause. It's also a best practice to actually specify the fields you are trying to fetch rather than *, though we all use * a lot when we're lazy.
Will A's answer makes me smile because it's technically what you asked for, though not what I expect you wanted.
Do you have a more detailed description of what data you're trying to extract, or was this just an example because you are having trouble figuring out joins?
-J

Categories