Reputation: 646
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
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
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