Mysql - Simple select Query question - is this bad code ?

Discussion in 'MySQL' started by Maxell, Nov 20, 2007.

  1. #1
    I use the following code style in my codes, is this a bad approach ? less effective ? less optimized ? if so what would be the best approach and optimized query for just fetching information from database..

    thanks for your time..
     
    Maxell, Nov 20, 2007 IP
  2. Kynlem

    Kynlem Peon

    Messages:
    14
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Instead of the for loop, use:
    
    while($r = mysql_fetch_assoc($q)) {
    echo "any field or anything you wnt to do with data";
    }
    
    PHP:
     
    Kynlem, Nov 20, 2007 IP
  3. Maxell

    Maxell Guest

    Messages:
    335
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I dont think if that would make any differece, can you please give some reasons ? it wont effect the performace of the query...
     
    Maxell, Nov 20, 2007 IP
  4. Kynlem

    Kynlem Peon

    Messages:
    14
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    By calling mysql_num_rows() you ask MySQL API to check the number of returned rows on every iteration of the loop.
     
    Kynlem, Nov 20, 2007 IP
  5. Petey

    Petey Peon

    Messages:
    68
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #5
    The while loop will automatically step through the result set in $q a row at a time and will close itself when there is no data left so you don't need the row count.

    Kynlem is right, this is more efficient as you don't make calls to mysql_num_rows() and you are not using the $i counter.
     
    Petey, Nov 21, 2007 IP
  6. Maxell

    Maxell Guest

    Messages:
    335
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #6
    thanks for the advice, I truly appreciate.. I got it, I will follow this style from now on..
     
    Maxell, Nov 21, 2007 IP