Fetching from database using PHP

If you have database, then of course you will need to fetch data out of it. Four methods are described below to fetch from database and whats the difference between them.

Required: PHP, MySQL.
Using:

SQL table

table1(
name varchar(20)
)

PHP query:

$query = "SELECT name FROM table1";
$rows = mysql_query($query);

PHP fetch functions:

$row = mysql_fetch_array($rows, $result_type);
$row = mysql_fetch_assoc($rows);
$row = mysql_fetch_row($rows);
$row = mysql_fetch_object($rows, 'class', $params);
Note: All parameters are not defined here but are explained below.
Explanation:

Methods to fetch are described below:

  1. mysql_fetch_array($rows, $result_type): First argument, $rows is same as we have described earlier. Second argument is the result type which has three values MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH, which is default and this argument is optional.
    • MYSQL_ASSOC is used when we want to use associative key or table name for fetching. So, if we want to echo result it would be like
      echo $row[‘name’];
    • MYSQL_NUM is used if we are going to use numbers as associative keys also called index. It would go like
      echo $row[0].
    • MYSQL_BOTH is used if you don’t know what you are going to use. With this way you can use both key and index.
  2. This is just the same as mysql_fetch_array() with result type argument as MYSQL_ASSOC. Syntax will be
    $row[‘name’];
  3. It is identical to mysql_fetch_array() with result type as MYSQL_NUM. Syntax will be
    echo $row[0];
  4. mysql_fetch_object($rows, ‘class’, $params): This is same as mysql_fetch_assoc() but instead of array this returns object of class ‘class’. That is it can be accessed by only with column name in table. Syntax would be:
    echo class->name;
    The last argument, $params, is used when parameters are needed to be passed in constructor of ‘class’, it has to be array. Also $params is optional.

Note: All the fetch function are almost equivalent in terms of performance.

         Also see PHP manual on these function.

Advertisements