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

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?

Related

sql show the last 4 rows from database

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.

how to update database sequentially using mysql

I have a long list from database which i want to update a field by name group. i want to update the first 30 to value '1' next 30 to value '2' and so on until the end
Any idea on how to go about it
$sql = mysqli_query($conn,
"UPDATE `tablename` SET `group` = '$value' WHERE id IN (SELECT id FROM tablename ORDER BY id desc LIMIT 0, 30)");
You have run into this limitation of mysql
You cannot update a table and select from the same table in a
subquery.
You could use an update join, but since limits are involved, you would once again run into the same issue. Since only a small number of records are involved, you could do a simple query to get the ids.
SELECT GROUP_CONCAT(id) FROM tablename ORDER BY id desc LIMIT 0, 30
Then use that in the next query
UPDATE `tablename` SET `group` = '$value' WHERE id IN (ids_from_above_query)
If you are worried about concurrent updates, start a transaction.
If your update is a one-time thing (and don't need to optimize it, e.g. do it all in one query), you can simply repeat the following query until you are finished:
update `tablename`
SET `group` = '$value'
where `group` is null
order by id desc
limit 30;
All group-values have to be null (or some other unused value) to begin with, so e.g. use update tablename SET group = null first, if they aren't.
And you probably want to do it all in a transaction.

Erase everything but last X entries from an SQL table?

Is there an MySQL query which would delete all values from a table, except the latest 20 entries (ordered by id)?
So let's say I have a table notifications, where 1000 notifications reside and I want to keep only latest 20.
If SQL is not enough for this, using php is optional.
I have a few ideas how to do this, but I don't really consider them efficient.
You can find the latest id, store it into local variable and then delete everything below this id:
set #tmp_id := (select id from notifications order by id desc limit 20,1);
delete from notifications where id <= #tmp_id;
I have not ran this, so I apologize if it doesn't work, but according to the SQL syntax for delete this should work.
DELETE FROM notifications ORDER BY id ASC LIMIT ((SELECT COUNT(*) FROM notifications)-20);
$result = $mysqli->query("SELECT ids FROM notifications");
$count = $result->num_rows;
$count -=20;
$result = $mysqli->query("DELETE FROM notifications ORDER BY id ASC LIMIT $count");

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

PHP select the biggest `id` value from MySQL table

I have a table with more than 300 000 rows and I need to select the highest value for the column 'id'. Usually, I will do like this:
SELECT id FROM my_table ORDER BY id DESC
... but this will cause slow queries and I don't want to use it. Is there a different way to solve this situation? id is auto increment and primary key.
Later Edit: It seems my full code is quite bad written, as I deduct from your comments. Below I posted a sample of the code I'm working and the tables. Can you suggest a proper way to insert the last ID+1 of table_x in two tables (including table_x itself). I have to mention that the script will be running more than once.
TABLE_X TABLE_Y
------------ ----------
id_x | value id_y | id_x
------------ ----------
1 | A 1 | 3
2 | B
3 | C
<?php
for($i=0; $i<10; $i++){
$result_x = mysql_query('SELECT id_x FROM table_x ORDER BY id_x DESC');
$row_x = mysql_fetch_array($result_x);
$next = $row_x['id_x'] + 1;
mysql_query('INSERT INTO table_x(id_x) VALUES("'.$next.'")');
mysql_query('INSERT INTO table_y(id_x) VALUES("'.$next.'")');
}
?>
Slightly better:
SELECT id FROM my_table ORDER BY id DESC LIMIT 1
Significantly better:
SELECT MAX(id) FROM my_table
Here is the right code you have to use.
mysql_query('INSERT INTO table_x(id_x) VALUES(NULL)');
$id = mysql_insert_id();
mysql_query("INSERT INTO table_y(id_x) VALUES($id)");
Depending on the context either
SELECT id FROM my_table ORDER BY id DESC LIMIT 1
or mysql_insert_id() in PHP or (SELECT LAST_INSERT_ID()) in MySQL
As other said, you should use the MAX operator:
SELECT MAX( id ) FROM my_table ORDER BY id DESC
As a general rule of thumb, always reduce the amount of records returned from the database. The database always is faster than your application program when operating on result sets.
In case of slow queries, please give EXPLAIN a try:
EXPLAIN SELECT id FROM my_table ORDER BY id DESC
vs.
EXPLAIN SELECT MAX( id ) FROM my_table ORDER BY id DESC
EXPLAIN ask MySQL's query optimizer how it sees the query. Look in the documentation, to learn how to read its output.
PS: I really wonder, why you need MAX(id). Even if your application gets the value back from the database, it is useless: Another process might just during the next CPU cycle have inserted a new record - and MAX(id) isn't valid any more.
I guess it is slow because you retrieve all 300 000 rows. Add LIMIT 1 to the query.
SELECT id FROM my_table ORDER BY id DESC LIMIT 1
Or use the MAX() operator.

Categories