Delete rows except last added 250 ones

Discussion in 'PHP' started by meannn, Feb 16, 2010.

  1. #1
    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:

     
    meannn, Feb 16, 2010 IP
  2. plog

    plog Peon

    Messages:
    298
    Likes Received:
    11
    Best Answers:
    1
    Trophy Points:
    0
    #2
    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.
     
    plog, Feb 16, 2010 IP
  3. n3r0x

    n3r0x Well-Known Member

    Messages:
    257
    Likes Received:
    4
    Best Answers:
    1
    Trophy Points:
    120
    #3
    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:
     
    n3r0x, Feb 16, 2010 IP
  4. koko5

    koko5 Active Member

    Messages:
    394
    Likes Received:
    14
    Best Answers:
    1
    Trophy Points:
    70
    #4
    koko5, Feb 16, 2010 IP