start blog post

Mysql_fetch_all: PHP's Missing Function

PHP has a ton of built-in functions (over 5700 as of this blog post), almost 50 of which deal with MySQL database manipulation. I don't think I normally use more than about 3 or 4 mysql_... functions, but one task I perform often is gather all of the returned rows into an array.

  // assume $conn is my database connection
  $query = "SELECT * FROM someTable WHERE someField = 'Some Value'";
  $result = mysql_query($q, $conn);
  $rows = array();
  while($row = mysql_fetch_assoc($r)) {
    $rows[] = $row;
  // $rows now holds all of my results

If I just have to do one query, that's fine. But on large projects I may have several queries on a single page. Any time I have to type something more than twice I quickly start looking for ways to abstract it into a reusable function, so here goes:

  function mysql_fetch_all($query, $conn) {
    $result = mysql_query($query, $conn);
    $rows = array();
    while($row = mysql_fetch_assoc($result)) {
      $rows[] = $row;
    return $rows;
  // all future queries become one-liners
  $employees = mysql_fetch_all("SELECT * FROM Employees", $conn);

Nothing Earth-shattering, but fewer keystrokes means fewer chances for error. What's your favorite PHP or SQL shortcut?

var tags = [];

  • share this post:
  • email a friend
  • float this post
  • digg this post
  • share on stumbleupon
  • submit to technorati
  • tweet this post

end blog post

most viewed this week

least viewed this week