Sergio
Sergio

Reputation: 822

PHP/MYSQL Query as a Function for Multi-Use

I am trying to clean a ton of select queries inside about 15 pages of a website and I thought using a function that then I can use to call all the different queries and tables, would reduce the clutter a bunch.

I am running into a problem and can't seem to figure out a way to get it right.

Here is the function:

function dbGet($conn, $table, $select, $where, $cond) {
   require($conn);
   if ( $stmt = $db->prepare(" SELECT $select FROM `" . $table . "` WHERE $where=? ")) {
      $stmt->bind_param("i", $cond);
      $stmt->execute();
      $result = $stmt->get_result();
      $rowNum = $result->num_rows;

      if ( $rowNum > 0 ) {
         while( $data = $result->fetch_assoc() ){
            return $data;
         }
      }
      $stmt->close();
   } else {
      die($db->error);
   }
   $db->close();
}

And here is how I call the function in the various different pages:

$settings = dbGet('php/connect.php', 'settings', '*', 'userId', $sessionId);
echo $settings->toName;

The problem I am running into, is that it is only displaying the first record from the settings table. I thought using the while loop in the function would return all the records. As a matter of fact, if I do a print_r for $data instead of return, I get all the records. How can I pass along all the records into the return $data to be access in any other page?

OR If you guys happen to have any suggestions of an existing function that is highly regarded and true-and-tested that I can implement instead of writing my own, please let me know.

Thanks.

Upvotes: 0

Views: 62

Answers (1)

smcjones
smcjones

Reputation: 5600

When return is triggered, the function ends and every other line of code after it is not executed. If you want to delay the return of your data until later in the function, then create a variable, assign value(s), and return the variable when you're ready.

For example, you can adapt your code to create an array for $data, like so:

function dbGet($conn, $table, $select, $where, $cond) {
    $data = array();
    ...
    while ( $row = $result->fetch_assoc() ) {
        $data[] = $row;
    }
    $stmt->close();
    ...

    $db->close();

    return $data;
}

Upvotes: 1

Related Questions