1

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!

2
  • return ['text' => $row['quote_text'], 'author' => $row['quote_author']] Commented Oct 29, 2015 at 18:01
  • Why do you need a while loop if you limit the query to one result? Commented Oct 29, 2015 at 18:03

2 Answers 2

1

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'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks dude! You are awesome.
1

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'];

2 Comments

won't you check if $row isn't null before accessing it's indices?
@ciriusrob Sure, but it wasn't a requirement. I'd also check for connection errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.