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.
return, you are effectively ending that function at the first pass of that loop. That's why you only see the first record.returning rows, maybe you want toyieldthem? See php.net/manual/en/language.generators.syntax.php.