'Assign output of PHP function to a variable
Here's my current code:
function get_coins() {
global $conn;
$new_sql = "SELECT * FROM marketcaps ORDER BY cap DESC LIMIT 25";
$new_result = $conn->query($new_sql);
while ($row = $new_result->fetch_assoc()) {
$id = $row["id"];
$coin = $row["coin"];
$cap = $row["cap"];
echo $coin . '~USD,';
}
}
$coins = get_coins();
Here's what I can't figure out:
The line $coins = get_coins();
is echoing all of the data from my function and I don't understand why. I know that my function has this line: echo $coin . '~USD,';
But why is it echoing when I add $coins = get_coins();
?
Shouldn't I have to add this instead?
$coins = get_coins();
$echo coins;
Basically I don't want to echo anything, I just want to assign the output to a variable. Is there a simple way to do that?
Solution 1:[1]
Here are the principles that I have baked in with my solution which returns the full resultset array:
- Don't use
global
, pass$conn
as a parameter to the function. - Don't declare single use variables, unless it dramatically improves readability or assists in the debugging process.
- Only query for the specific columns and rows that you intend to process.
Suggested Code:
function get_coins($conn): array {
return $sql
->query("SELECT id,coin,cap
FROM marketcaps
ORDER BY cap DESC
LIMIT 25")
->fetch_all(MYSQLI_ASSOC);
}
foreach (get_coins($conn) as $row) {
// ... reference $row['id'] , $row['coin'] , $row['cap'] during your processes
}
Solution 2:[2]
You need to add a return
statement to your function, and as you are dealing with multiple rows, collate them into an array (index by ID).
http://php.net/manual/en/function.return.php
function get_coins()
{
global $conn;
$coins = array();
$new_sql = "SELECT * FROM marketcaps ORDER BY cap DESC LIMIT 25";
if( $new_result = $conn->query($new_sql) )
{
while( $row = $new_result->fetch_assoc() )
{
$coins[ $row["id"] ] = $row["coin"] . '~USD,';
}
}
return ( !empty( $coins ) ) ? $coins : null;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |