Select question (my sql and php)

Discussion in 'PHP' started by legend19892008, Jun 28, 2008.

  1. #1
    plz i want to ask a question in select statment
    i want to select the last 3 entries in the table products
    i tried a code but it selects all the entries
    could u help me plz:)
    <?
    $conn=mysql_connect("localhost","root","root");
    mysql_select_db('project3');
    $sql="select * from product ORDER BY id DESC";
    $rs=mysql_query($sql);
    $i=1;
    while ($data=mysql_fetch_array($rs))
    {
    if (i<3)
    {
    echo $data['id'].$data['name']."<br>";
    }
    $i++;
    }
    
    
    ?>
    Code (markup):

     
    legend19892008, Jun 28, 2008 IP
  2. King Goilio

    King Goilio Member

    Messages:
    200
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    33
    #2
    what dose this output?
    try fixing
    
    if (i<3)
    
    Code (markup):
    change i to $i
     
    King Goilio, Jun 28, 2008 IP
  3. legend19892008

    legend19892008 Peon

    Messages:
    34
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    thnxxxxxx so much
    it worked
     
    legend19892008, Jun 28, 2008 IP
  4. King Goilio

    King Goilio Member

    Messages:
    200
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    33
    #4
    no problem
     
    King Goilio, Jun 28, 2008 IP
  5. David Pankhurst

    David Pankhurst Member

    Messages:
    39
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    43
    #5
    You can also change the sql:

    $sql="select * from product ORDER BY id DESC";

    to

    $sql="select * from product ORDER BY id DESC LIMIT 3";

    this returns only 3 records - not a big issue on a small database, but if you have a large number of product ids (id) it could return a lot of data.
     
    David Pankhurst, Jun 28, 2008 IP
  6. legend19892008

    legend19892008 Peon

    Messages:
    34
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    thanks david so much
     
    legend19892008, Jun 29, 2008 IP
  7. IGiveMoney

    IGiveMoney Peon

    Messages:
    116
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #7
    in your select statement you can get specific as well.

    Something like
    $sql = "SELECT name, address, email from product ORDER BY id DESC LIMIT 3";

    That works as well.
     
    IGiveMoney, Jun 29, 2008 IP
  8. David Pankhurst

    David Pankhurst Member

    Messages:
    39
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    43
    #8
    My pleasure - and as IGiveMoney mentioned, you can reduce the # fields for each record - great if you have very long fields that don't need to be read in (like a large product description, for example).
     
    David Pankhurst, Jun 29, 2008 IP