Get first/last value from SQL selection using PHP - php

I have a SQL query in my php file (I use this file to calculate graphic timeblocks based on starting time and duration of an event; starttime and duration are my columns in SQL table).
How can I print/get last or first value from selection below using php? I mean first or last value from column 'starttime' to be precise.
$query1=mysqli_query($db,"select * from LISTS where category='planner'
order by date,timestart asc");
I googled since I am very much beginner but results did not make much sense because I don't have much skills yet. Therefore I am asking you.
Thanks in advance. Also can you please explain in very primitive way, some terms I might not understand at this point.

If you wan't both the first and last value in one MySql state you can use "Union". The UNION operator is used to combine the result-set of two or more SELECT statements.
To get either first or last value use "limit" and set this to 1, then order by asc or desc.
Example:
select * from LISTS where category='planner' order by date,timestart asc
limit 1) union (select * from LISTS where category='planner' order by
date, timestart desc limit 1

So I decided to find only first value based on my selection. I had to show it on the page, this is what worked for me.
$query3=mysqli_query($db,"select datetime from LISTS where
category='planner' order by date,timestart asc");
$SelectionArray=mysqli_fetch_array($query3);
$FIRSTdatetime=reset($SelectionArray);
echo $FIRSTdatetime;

Related

SQL PHP get full row with MAX i a single table

i have one table collecting scores and other informations like the date and the user id. I would like to get the MAX of the current month and the other fields of the row. I'm having a problem to get the other informations since with functions we cannot get other fields.
I think i should do an inner join but i don't how to make it.
Thank you.
Your question is rather vague. But if you want one row, then the idea for the solution is order by and fetch first row only.
In standard SQL, the query would look like:
select t.*
from t
where extract(year from datecol) = extract(year from current_date) and
extract(month from datecol) = extract(month from current_date)
order by t.score desc
fetch first 1 row only;
Databases often differ on database functions. For instance, many use year() and month() functions, rather than extract(). Similarly, many databases do not support fetch first 1 row only, using limit or select top instead.
Thank you, yes it does work doing this way but the idea was to use MAX (for learning purpose).
I have scores table, with the following fields: id, score, date, user_id
I would like, using MAX, to get the best and latest score of the current month along with the other fields (ie the id, date and user_id).

Get previous 10 row from specific WHERE condition

Im currently working on a project that requires MySql database and im having a hard time constructing the query that i want get.
i want to get the previous 10 rows from the specific WHERE condition on my mysql query.
for example
My where is date='December';
i want the last 10 months to as a result.
Feb,march,april,may,june,july,aug,sept,oct,nov like that.
Another example is.
if i have a 17 strings stored in my database. and in my where clause i specify that WHERE strings='eyt' limit 3
Test
one
twi
thre
for
payb
six
seven
eyt
nayn
ten
eleven
twelve
tertin
fortin
fiftin
sixtin
the result must be
payb
six
seven
Thanks in advance for your suggestions or answers
If you are using PDO this is the right syntax:
$objStmt = $objDatabase->prepare('SELECT * FROM calendar ORDER BY id DESC LIMIT 10');
You can change ASC to DESC in order to get either the first or the last 10.
Here's a solution:
select t.*
from mytable t
inner join (select id from mytable where strings = 'eyt' order by id limit 1) x
on t.id < x.id
order by t.id desc
limit 3
Demo: http://sqlfiddle.com/#!9/7ffc4/2
It outputs the rows in descending order, but you can either live with that, or else put that query in a subquery and reverse the order.
Re your comment:
x in the above query is called a "correlation name" so we can refer to columns of the subquery as if they were columns of a table. It's required when you use a subquery as a table.
I chose the letter x arbitrarily. You can use anything you like as a correlation name, following the same rules you would use for any identifier.
You can also optionally define a correlation name for any simple table in the query (like mytable t above), so you can refer to columns of that table using a convenient abbreviated name. For example in t.id < x.id
Some people use the term "table alias" but the technical term is "correlation name".

How do I retrieve data and present it earliest in date order through PHP?

I want to get data from my database and present each field in separate divs - which I can do. However it is ordered earliest to latest meaning the first bits of data are at the top. How do I get it the other way round? Is it something I have to do in phpMyAdmin?
I am a Noob, please help. (thanks in advance).
Without seeing your actual SQL statements and tables its hard to give a definitive answer.
However, you're looking for the ORDER BY clause. You can order something by a field in either Ascending (1, 2, 3) or Descending (3, 2, 1) Order.
For example:
SELECT * FROM Employees ORDER BY HireDate ASC
vs
SELECT * FROM Employees ORDER BY HireDate DESC
To get it in reverse order.
From what I have understood is that you want to display the data in descending order. Use ORDER BY clause, which helps you to sort the data either in ascending or descending order.
for example:
SELECT * FROM shop
ORDER BY date DESC;

PHP, MYSQL: Order by date but empty dates last not first

I fetch an array with todo titles and due dates from MySQL. I want to order it by date and have the oldest on top. But there are some todos without a date. These todos I don't want to show at first positions but rather at the bottom of my list. Unfortunately MySQL put the empty ones first.
Is there any way I can do it in one query (can't use MySQLi, using CI's ActiveRecord). I could run a second query for all todos without dates and put them at the bottom. But I'd like to make it in one query – if possible?
You can do it in MySQL with the ORDER BY clause. Sort by NULL first, then the date.
SELECT * FROM your_table ORDER BY (date_column IS NULL), date_column ASC
Note: This assumes rows without a date are NULL.
Yes
SELECT *
FROM table
ORDER BY CASE your_date
WHEN '' THEN 'b'
ELSE 'a'
END,
date ASC
possibly add a NVL( thedate, to_date('2099-12-31','yyyy-mm-dd')) in the order by clause
You can use this:
select * from my_table
order by if(isnull(my_field),1,0),my_field;
Well, as a pure MySQL answer, I would probably do it like this.
select todo.title, todo.due_date
from todo
order by ifnull(todo.due_date, '9999-12-31')

PHP - MySQL display highest ID number

What SQL query would I use to display the newest entry?
Details:
id is the primary field. I have other fields but that are not related to when they were added.
ORDER BY SomeColumn DESC
LIMIT 1
or
use the MAX() function
Since you didn't give any details about your table it is hard to answer
SELECT * from yourTable ORDER BY `id` DESC LIMIT 1;
Another (better) way would be to have a "date_added" column (date_added TIMESTAMP DEFAULT CURRENT_TIMESTAMP) so you could order by that column descending instead. Dates are more reliable than ID-assignment.
not sure if this is what your looking for but I use mysql_insert_id() after inserting a new row
The auto incremented ID columns are not always the latest records inserted, I've remember really painful experience with this behavior. Conditions where specific, it was mysql 4.1.x at the time and there was almost 1 million records, where 1 out of 3 deleted everiday, and others re inserted in the next 24hours. It made a huge mess when I realize ordering them via ID was not ordering them by age....
Since then, I use a specific column for doing age related sorts, and populating these fields with date = NOW() at each row insert.
Of course it will work to found the latest record as you want, doing an ORDER BY date DESC LIMIT 0,1on your query
SELECT Primary_Key_Field FROM table ORDER BY Primary_Key_Field DESC LIMIT 1
Replace Primary_Key_Field and table obviously :)

Categories