所以我基本上试图通过php函数从SQL获取quote_author和quote_text结果,然后以风格化的html显示它。当我调用函数时我想获得2个变量$ quote_text和$ quote_author,所以我可以将它们放在html中的两个separe div中,因为它们的风格化程度不同。
这是我的代码
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'];
提前致谢!
答案 0 :(得分:1)
您应该使用return
语句从函数返回结果。您也不需要while
循环,因为查询只返回一行。
$row = mysqli_fetch_assoc();
return $row;
然后来电者做:
$row = get_quotes();
if ($row) {
echo $row['quote_text'];
echo $row['quote_author'];
}
答案 1 :(得分:1)
您应该执行以下操作:
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'];