Hello mates, I want to delete all rows in a table except last added 250 ones. I have this script, but it deletes all rows except first 250 ones. I need your help, thanks. $query="SELECT * FROM looks"; $result=mysql_query($query); echo mysql_error(); $all_looks = array(); for($i=0; $i<mysql_num_rows($result); $i++){ $row = mysql_fetch_array($result); $all_looks[$i] = $row["id"]; } for($i=0; $i<count($all_looks)-251; $i++){ mysql_query("DELETE FROM looks WHERE id='".$all_looks[$i]."';"); } echo mysql_error(); PHP:
The rows in a database table have no order. Think of them as this huge pile of rows of data. The only time they have order is when you pull them out and assign an order to them (using the 'ORDER BY' clause of a query). That may be alphabetically by last name, numerically by age or by a date field. So, you have to define, using the data in those random rows, what constitutes the first 250 rows. Is there a date field that you can use to order them? Or maybe an auto-incrementing id field? Once you are able to identify a field that you can assign order to, then you can use the 'LIMIT' clause of mysql.
Something like this should do it. $ID = mysql_result(mysql_query("SELECT id FROM `Table` ORDER BY id DESC limit 250,1"),0); mysql_query("DELETE FROM `Table` WHERE id < '".$ID."'"); PHP: