mysql_fetch_array, mysql_fetch_assoc, mysql_fetch_object

Viewed 18587

The functions are all very similar:

mysql_fetch_array(), mysql_fetch_assoc(), mysql_fetch_object()

I have recently started using mysql_fetch_object as I am doing alot more OOP with PHP.

But what are peoples opinions on which one is best to use and why, and maybe which scenario they are best to be used in.

Thanks for your thoughts!

4 Answers

mysql_fetch_array() fetches a result row as an associative array, a numeric array, or both. It returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how $result_type is defined.

By using MYSQL_NUM, you only get number indices (as $row[0], $row1, etc) i.e., numeric array.

By using MYSQL_ASSOC, you only get associative indices (as $row["id"], $row["name"], etc) i.e., associative array.

By using MYSQL_BOTH (default), you’ll get an array with both associative and number indices. (as $row[0], $row["name"], etc) i.e., both numeric array and associative array.

mysql_fetch_assoc() fetches a result row as an associative array. (column names as key).

mysql_fetch_object() fetches the result row as an object.

It returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead.

To me there are adantages of using mysql_fetch_assoc() in that you can use the array functions such as array_walk and uasort().

Suppose we have following table

Name      CountryCode
-----     ----------
Bangladesh  BD
Pueblo     USA
Arvada     USA

$query = "SELECT Name, CountryCode FROM City";

$result = mysqli_query($connection, $query)

  1. mysqli_fetch_object (data can be fetch as object)

     while ($obj = mysqli_fetch_object($result)) {
        printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
     }
    
  2. mysqli_fetch_assoc (fetch as associative array i.e. key)

    while ($row = mysqli_fetch_assoc($result)) { printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]); }

  3. mysqli_fetch_array (numeric & associative both)

    while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) { printf("%s (%s)\n", $row[0], $row[1]); }

    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { printf("%s (%s)\n", $row["Name"], $row["CountryCode"]); }

Related