in reply to Re^2: Retrieving multiple records from database
in thread Retrieving multiple records from database

The array that "fetchrow_array()" returns is the selected columns (each in their own element of the array) from a single row. If your query grabbed multiple rows, you need to keep calling fetchrow_array() to get the next row, and so on. Undef will indicate you're done.

fetchall_arrayref() fetches all of the rows, in a multidimensional array where the 2nd dimension is the columns.


Dave

  • Comment on Re^3: Retrieving multiple records from database

Replies are listed 'Best First'.
Re^4: Retrieving multiple records from database
by bradcathey (Prior) on Oct 17, 2004 at 11:52 UTC

    Thanks, davido, I ended up with this in my final app:

    while ($row = $sth->fetchrow_array()) { push (@categories, $row); }

    I guess fetchrow and fetchall we appropriately named ;^) Now, I wish there were a fetchcol that just retrived a known column of a given row (intersection, so selectcol_arrayref wouldn't work) so I don't have to do:

    $single_value = $categories[0];

    after the fetch, and could just do:

    $single_value = $sth->fetchcol_justone;

    —Brad
    "Don't ever take a fence down until you know the reason it was put up." G. K. Chesterton

      You have to build the column into your SQL statement. The first statement here will select all columns.

      SELECT * FROM mytable WHERE age = ?

      And this will select just one column:

      SELECT firstname FROM mytable WHERE age = ?

      In the case of the second SQL statement, fetchrow_array() will return an array of one single element.

      There is a pretty good basic SQL tutorial at http://www.w3schools.com/sql/default.asp.

      Another alternative is the $slice parameter of the fetchall_arrayref() method. By passing an anonymous arrayref containing the element numbers you're after, you can "slice" the arrayref for each row so that only certain columns are seen. This is documented in DBI.


      Dave