Tsvetilin Boynovski
Tsvetilin Boynovski

Reputation: 646

Save SQL result in php function as array

so I am basically trying to take the quote_author and quote_text results from SQL through a php function and then display it in stylized html. When I call the function I want to get 2 variables $quote_text and $quote_author, so I can put them in two separe divs in html, because they are stylized differently.

This is my code

function get_quotes(){

$connection = mysqli_connect("localhost","xxx","xxx","xxx");
$sql = "SELECT quote_text, quote_author FROM quotes ORDER BY rand() LIMIT 1";
$result = mysqli_query($connection,$sql);
while($row = mysqli_fetch_assoc($result)) {
       //how can I get the two results $row['quote_text'] and $row['quote_author'] 
       //out of the function
   }
}

get_quotes();
echo $row['quote_text'];
echo $row['quote_author'];

Thanks in advance!

Upvotes: 1

Views: 60

Answers (2)

Piyin
Piyin

Reputation: 1834

You should do something like:

function get_quotes(){
    $connection = mysqli_connect("localhost","xxx","xxx","xxx");
    $sql = "SELECT quote_text, quote_author FROM quotes ORDER BY rand() LIMIT 1";
    $result = mysqli_query($connection,$sql);
    return mysqli_fetch_assoc($result);
}

$row = get_quotes();
echo $row['quote_text'];
echo $row['quote_author'];

Upvotes: 1

Barmar
Barmar

Reputation: 781096

You should use a return statement to return the results from the function. You also don't need a while loop, since the query only returns one row.

$row = mysqli_fetch_assoc();
return $row;

Then the caller does:

$row = get_quotes();
if ($row) {
    echo $row['quote_text'];
    echo $row['quote_author'];
}

Upvotes: 1

Related Questions