sql show the last 4 rows from database - php

How can i display only the last 4 rows from the DataBase?
This is my code:
$sql3 = "SELECT *
FROM `event_guests`
WHERE `idevent`='".$idevent."'
ORDER BY `id` ASC
LIMIT 4";
Note that i don't want to use DESC to order them in reverse because i want the last row to be the last row and not the first.
Alse just display 4 rows even if there is more.

It sounds like you want two order bys:
SELECT eg.*
FROM (SELECT eg.*
FROM event_guests eg
WHERE eg.idevent = ?
ORDER BY eg.id DESC
LIMIT 4
) eg
ORDER BY id ASC;
The ? is for a parameter placeholder. You should learn how to use them rather than munging query strings with parameters. What you are doing is very dangerous (makes the code subject to SQL injection attacks) and can affect the performance of queries.

Related

RAND returns suplicates and sometimes no values

I'm trying to make a quiz using mysql and php
I want to fetch questions randomly from the database
I have a truble with rand function
sometimes it seturns no value and returns also duplications
I tried to find a solution on the net but couldn't make it
this is the part of code that generate the problem
$link=mysqli_connect("localhost","root","","database");
$req="SELECT DISTINCT *
FROM `qst_s`
WHERE `id_qst` = ROUND( RAND()*49 ) + 1 AND `level` = '1' LIMIT 40";
$result=mysqli_query($link,$req);
$question=$result->fetch_assoc();
I have 50 questions in my database level 1 by the way
The simplest way of selecting random rows from the MySQL database is to use "ORDER BY RAND()" clause in the query.
SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;
The problem with this method is that it is very slow. The reason for it being so slow is that MySQL creates a temporary table with all the result rows and assigns each one of them a random sorting index. The results are then sorted and returned.
Your query would look like this:
$req="SELECT DISTINCT *
FROM `qst_s`
WHERE `level` = '1'
ORDER BY RAND()
LIMIT 40";

Order by field not working,but no error

I have a query like this,
select * from my_table where `status`='1' ORDER BY FIELD(city_id,548) ASC;
My purpose is to show all records from the table, but records with city_id=548 should come first.
Currently its showing all records but no desired sorting! Any ideas?
Actually it is working but you need to change it to DESC because FIELD() returns the index of the value in the parameter.
Other than FIELD() which accepts multiple parameters, you can alternatively use = if you only have one condition.
ORDER BY (city_id = 548) DESC
when city_id = 548 is true, it returns 1 otherwise 0 that is why we used DESC.
Try like this
descending order in sql is denoted by DESC keyword I think other values are smaller than 548 that's why it's not work as you expect
select * from my_table where `status`='1' ORDER BY FIELD(city_id,548) DESC;

PHP-Mysql Delete from entry number 1000 till the last entry

Hello there i would like to use a DELETE statement in Mysql in order to delete all the entries after the 1000th entry, but on the same time ordering the entries by descending order of a column... This is the code i am using:
mysql_query("DELETE FROM 'tblname' WHERE #i IN (1000,ROW_COUNT()) ORDER BY points DESC");
Although no error occurred, it doesnt seem to work for some reason.... i am having trouble in the WHERE clause... can anyone help on that ?
You have quotes around your table name:
mysql_query("DELETE FROM 'tblname' WHERE #i IN (1000,ROW_COUNT()) ORDER BY points DESC");
Replace them with backticks as such:
mysql_query("DELETE FROM `tblname` WHERE #i IN (1000,ROW_COUNT()) ORDER BY points DESC");
Edit: (deleting records)
Try:
mysql_query("DELETE TOP (1000) FROM `tblname` ORDER BY points DESC");
You can also try:
DELETE FROM tablename ORDER BY points DESC LIMIT 1000 *
Assuming this is a column named id:
mysql_query("DELETE FROM tablename WHERE id > 1000");
That would leave the first 1,000 rows and remove every other entry.
A few more examples:
DELETE FROM `table` WHERE `id` < 1000
DELETE FROM `table` WHERE `id` LIMIT 0, 1000
DELETE FROM `table` WHERE ID BETWEEN 1 AND 999
Footnote:
If you are using a variable for your table name (which could be a possibility, without seeing full code), use the following, IF this is the case; many do.
$tblname = "your_table_name";
mysql_query("DELETE FROM `".$tblname."` WHERE #i IN (1000,ROW_COUNT()) ORDER BY points DESC");
You should also consider using mysqli_* functions with prepared statements or PDO. The mysql_* functions are deprecated and will be removed from future releases.
See this tutorial: PDO vs. MySQLi: Which Should You Use?
Also, consult this article on SO: How can I prevent SQL injection in PHP?

IDs not sorting

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".

displaying random row from last 100 entries?

I'm currently displaying a random row from all the entries and that works fine.
SELECT * FROM $db_table where live = 1 order by rand() limit 1
now, i'd like to limit it to the last 100 entries in the db.
every row in the db has an ID and a timestamp.
it's a small database, so overhead-minimization is not a priority.
thanks!
EDIT:
Still can't get it running.. I get a mysql_fetch_array error:
"Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
Here's all of my code:
<?php $sql = "SELECT * FROM
(SELECT * FROM $db_table ORDER BY $datetime DESC LIMIT 100)
ORDER BY rand() LIMIT 1";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {
echo "".$row['familyname']."";
} ?>
Thanks again!
This is what I came up with off the top of my head. I've tested it and it works in SQLite, so you shouldn't have much trouble with MySQL. The only change was that SQLite's random function is random() not rand():
SELECT * FROM
(SELECT * FROM $db_table ORDER BY $timestamp DESC LIMIT 100)
ORDER BY rand() LIMIT 1
This page has a pretty detailed writeup on how to optimize an ORDER BY RAND()-type query. It's actually too involved for me to explain adequately on SO (also, I don't fully understand some of the SQL commands used, though the general concept makes sense), but the final optimized query makes use of several optimizations:
First, ORDER BY RAND(), which uses a filesort algorithm on the entire table, is dropped. Instead, a query is constructed to simply generate a single random id.
At this stage, an index scan is being used, which is even less efficient than a filesort in many cases, so this is optimized away with a subquery.
The WHERE clause is replaced with a JOIN to reduce the number of rows fetched by the outer SELECT, and the number of times the subquery is executed, to just 1.
In order to account for holes in the ids (from deletions) and to ensure an equal distribution, a mapping table is created to map row numbers to ids.
Triggers are used to automatically update & maintain the mapping table.
Lastly, stored procedures are created to allow multiple rows to be selected at once. (Here, ORDER BY is reintroduced, but used only on the result rows.)
Here are the performance figures:
Q1. ORDER BY RAND()
Q2. RAND() * MAX(ID)
Q3. RAND() * MAX(ID) + ORDER BY ID
100 1.000 10.000 100.000 1.000.000
Q1 0:00.718s 0:02.092s 0:18.684s 2:59.081s 58:20.000s
Q2 0:00.519s 0:00.607s 0:00.614s 0:00.628s 0:00.637s
Q3 0:00.570s 0:00.607s 0:00.614s 0:00.628s 0:00.637s

Categories