cannot figure out MySQL ORDER BY - php

I am pretty new to MySQL...so I am sure this is probably an easy fix for someone...I've tried tutorials and other help topics, but can't figure out why it isn't working.
I have a data table with an auto incrementing index. I want to select the last 2 rows of the table. This is what I have:
SELECT * FROM tburg_golf ORDER BY 'index' DESC LIMIT 2
For some reason though, it gives me the first two rows. I've tried removing the limit, changing DESC to ASC...everything I can think of.
If curious, this is part of a larger piece of code:
$result = mysql_query("SELECT * FROM tburg_golf ORDER BY 'index' DESC LIMIT 2");
while($row = mysql_fetch_assoc($result)) {
$date = $row['date'];
$day = $row['day'];
$time = $row['time'];
$icon = $row['icon'];
$forecast = $row['forecast'];
$updated = $row['updated'];
echo $date.$day.$time.$icon.$forecast.$updated.'<p>';
}

SELECT * FROM tburg_golf ORDER BY `index` DESC LIMIT 2
If you type 'index' MySQL will ORDER BY the string 'index', which is the same for all tuples, instead of your column index.

You're ordering by 'index' which is a string constant. Column names are instead surrounded by `
Provided your auto incrementing column is actually called index, this will work;
SELECT * FROM tburg_golf ORDER BY `index` DESC LIMIT 2
Ordering by 'index' will sort every line by the same string, which basically will give you rows in random order.

Is there a field in the table called "index"?
If there is I believe the word index is a reserved word in MySQL which is why it might not work. Either rename the field or wrap it with ` instead of ' e.g.
SELECT * FROM tburg_golf ORDER BY `index` DESC LIMIT 2

Related

Can't retrieve zero values when using COUNT and GROUP together

I'm struggling with a MYSQL query, when using COUNT and GROUP together it's excluding any rows that have a count of 0. I understand why this is happening but can't work out how to get around it. I've read up on potential solutions presented to those with a similar problem but I cannot see the link between the two that would allow me to solve it.
Can anybody help?
$query = "SELECT id, class_date, class_id, COUNT(*) AS reserve_count
FROM bookings
WHERE booking_status='#RESERVE#'
GROUP BY class_date, class_id
ORDER BY class_date ASC, class_id ASC" ;
$result = mysqli_query($sql,$query);
while($row = mysqli_fetch_assoc($result)) {
$bookings[$row['id']] = array('class_date' => $row['class_date'], 'class_id' => $row['class_id'], 'reserve_count' => $row['reserve_count']);
}
Logically, there shouldn't be any row with zero count because booking table should only have classes that are booked.

How to get the first ID with SQL

I am trying to get the first id with a specific date.
So this is my code:
$checkm = "SELECT FIRST(id) FROM times WHERE date='2014-03-07'";
$resultm = mysqli_query($con,$checkm);
I have a table called times and there are some columns. Two of them are date and id.
I am trying to get the first row's id with the date 2014-03-07.
EDIT: Fixed!
$checkm = "SELECT id FROM times WHERE date='2014-03-06' ORDER BY id ASC LIMIT 1";
$resultm = mysqli_query($con,$checkm);
while($row = mysqli_fetch_array($resultm)) {
$resultm1 = $row['id'];
}
You probably want the minimum id.
SELECT min(id)
FROM times
WHERE date = '2014-03-07'
pretty straightforward...
SELECT id FROM times WHERE date='2014-03-07' ORDER BY id ASC LIMIT 1

SQL ORDER BY not working

Get the latest 4 donations that come into the system .
Donation IDs are auto incremented (201 , 202, 203 , 204) .. therefore I wanted to order by DESC to get the latest 4 donations.
$resultsdonations = mysql_query("SELECT * FROM donationstable ORDER BY 'donation_id' DESC LIMIT 0,4 ");
Remove the apostrophes around 'donation_id' and the 0 is unnecessary in the LIMIT clause considering your requirement:
$resultsdonations = mysql_query(
"SELECT * FROM donationstable ORDER BY donation_id DESC LIMIT 4");
Try this:
$resultsdonations = mysql_query("SELECT * FROM donationstable ORDER BY donation_id DESC LIMIT 0,4 ");
(drop the ' around the donation_id column)
You don't need the quotes around donation_id. Just use .. BY donation_id DE ..
As the other answers have pointed out, you must remove the quotes from around donation_id.
As it currently stands, you are not sorting by the value in the donation_id column, but rather by the string literal 'donation_id', which is constant for each record and therefore results in an indeterminate ordering.

SELECT * FROM table_name ORDER BY column_name?

ok so i coded in a news section and everytime i insert new news,its shows below the old one.
i want to make it ORDER BY id but make it start like backwards.i dont know how to explain but yeh
i want them to be ordered by the newest added by the id so if the 1st row that was inserted's id is 1 then i want it to show below the next id.
so row with id = 2 will be here
so row with id = 1 will be here
thats how i want it to be, instead of it being like this
so row with id = 1 will be here
so row with id = 2 will be here
.
Sorry for my bad explanation i hope this is understandable
heres my code so far
<?php
require("include/config.php");
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id");
while($row = mysql_fetch_array($sqlnews)) {
$dbdate = $row['date'];
$dbnews = $row['news'];
echo "<h1><strong>$dbdate</strong></h1>";
echo "<div class='content'>$dbnews</div><br><br>";
}
?>
add DESC in your ORDER BY clause
SELECT * FROM news ORDER BY id DESC
by default, it is in ASC mode.
SELECT * FROM news ORDER BY id DESC
DESC is the descending keyword ASC is ascending
If you specify neither then default behaviour is ascending
Just use DESC keyword in your sql query.
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");
However, it isn't really such a good idea to use id, because semantically, there is nothing preventing somebody from changing the sequence which counts up automatically assigning the ID.
Therefore, you should add a column created_at. Everytime you insert a row, you can use the SQL function NOW().
The advantage is that you can say:
SELECT * FROM news WHERE created_at <= NOW() ORDER BY created_at DESC
This means that you can schedule news items ahead of time, and it will automatically display when the date/time arrives!
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");
try this:
just have to add
order by id DESC
Just replace your code by this code:
<?php
require("include/config.php");
$sqlnews = mysql_query("SELECT * FROM news ORDER BY id DESC");
while($row = mysql_fetch_array($sqlnews)) {
$dbdate = $row['date'];
$dbnews = $row['news'];
echo "<h1><strong>$dbdate</strong></h1>";
echo "<div class='content'>$dbnews</div><br><br>";
}
?>

Get total rows count of table

I want to get all rows count in my sql.
Table's first 2 columns look like that
My function looks like that
$limit=2;
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $total, $datetime, $title, $content);
$stmt->store_result();
$count = $stmt->num_rows;
if ($count > 0) {
while ($stmt->fetch()) {
Inside loop, I'm getting exact value of $total, but MySQL selects only 1 row - row with id number 1. (and $count is 1 too)
Tried this sql
SELECT id,dt,title,content FROM news ORDER BY dt DESC LIMIT 2
All goes well.
Why in first case it selects only 1 row? How can I fix this issue?
for ex my table has 5 rows. I want to get 2 of them with all fields, and get all rows count (5 in this case) by one query.
Remove COUNT(*). You will only ever get 1 row if you leave it in there.
Try adding GROUP BY dt if you want to use COUNT(*) (not sure why you're using it though).
EDIT
Fine, if you insist on doing it in a single call, here:
$sql = "SELECT id,(SELECT COUNT(id) FROM news) as total,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
This is likely cause by the variable $limit being set to 1, or not being set and mysql defaulting to 1. Try changing your first line to
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC";
EDIT
Change to:
$sql = "SELECT SQL_CALC_FOUND_ROWS,id,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
And then use a second query with
SELECT FOUND_ROWS( )
to get the number of rows that match the query
This totally wreaks of a HW problem... why else besides a professor's retarded method to add complexity to a simple problem would you not want to run two queries?
anyways.... here:
SELECT id, (SELECT COUNT(*) FROM news) AS row_count, dt, title, content FROM news ORDER BY dt DESC LIMIT

Categories