#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2000
    Posts
    41
    Rep Power
    15
    Here are two code examples of PHP grabbing data from MySQL. Just wondering which one is more efficient. If you know of a better means, please post it by all means.

    <BLOCKQUOTE><font size="1" face="Verdana,Arial,Helvetica">code:</font><HR><pre>
    Code Example 1:

    $query="SELECT * FROM table";
    $result=mysql_query($query);
    $num=mysql_numrows($result);

    $i=0;
    while ($i < $num) {

    $id=mysql_result($result,$i,"id");
    $name=mysql_result($result,$i,"name");

    print "$id - $name<br>n";

    ++$i;
    }
    [/code]

    or:

    <BLOCKQUOTE><font size="1" face="Verdana,Arial,Helvetica">code:</font><HR><pre>
    $query = "select * from table";
    $result = mysql_query($query);
    $num = mysql_numrows($result);

    while($row = mysql_fetch_object($result)) {

    print "$row->id<br>";
    [/code]
  2. #2
  3. Banned (not really)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Dec 1999
    Location
    Brussels, Belgium
    Posts
    14,646
    Rep Power
    4492
    It seems like the second one would be faster, I guess it depends how many values you are getting out of each row returned.

    If you are getting a row with say 10-20 items, then it seems like it'd be faster to fetch the whole thing into an object or array, and then just use $row->id, $row->name, etc...

    If you are only returning one or two things, then it seems like it'd be faster to just automatically assign that a variable, rather than creating a whole object.

    of course, i'm no professional and the actual speed difference is probably very small.

    the only extra info I can add is to put your $result = mysql_fetch_object($result) into an if statement. this is good if you aren't sure that anything will be returned from the query.

    <BLOCKQUOTE><font size="1" face="Verdana,Arial,Helvetica">code:</font><HR><pre>
    $query = mysql_db_query($query_statement);
    if ($result = mysql_fetch_object($query))
    {
    do {
    //Something returned...
    //Print out values...
    } while ($result = mysql_fetch_object($query));
    }
    else
    {
    //Nothing returned...
    }
    [/code]

    Don't know if this helps or not...if not, spend my $0.02 on something nice...

    ---John Holmes
    ---www.SepodatiCreations.com

Similar Threads

  1. Check MySQL Version thru PHP
    By wolftrap1 in forum PHP Development
    Replies: 2
    Last Post: February 11th, 2004, 08:51 PM
  2. Replies: 5
    Last Post: February 11th, 2004, 02:18 AM
  3. Replies: 0
    Last Post: February 10th, 2004, 11:44 PM
  4. Replies: 0
    Last Post: January 30th, 2004, 01:22 PM
  5. PHP 5 (MYSQL vs. SQLite)
    By ignition in forum PHP Development
    Replies: 1
    Last Post: January 23rd, 2004, 12:13 PM

IMN logo majestic logo threadwatch logo seochat tools logo