将php函数中的SQL结果另存为数组
所以我基本上是试图通过php函数从SQL中获取quote_author和quote_文本结果,然后用样式化的html显示它。当我调用函数时,我想得到两个变量$quote_text和$quote_author,这样我就可以把它们放在html中的两个separe div中,因为它们的样式不同 这是我的密码将php函数中的SQL结果另存为数组,php,mysql,sql,function,Php,Mysql,Sql,Function,所以我基本上是试图通过php函数从SQL中获取quote_author和quote_文本结果,然后用样式化的html显示它。当我调用函数时,我想得到两个变量$quote_text和$quote_author,这样我就可以把它们放在html中的两个separe div中,因为它们的样式不同 这是我的密码 function get_quotes(){ $connection = mysqli_connect("localhost","xxx","xxx","xxx"); $sql = "SELEC
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'];
提前谢谢 应该使用
return
语句从函数返回结果。您也不需要while
循环,因为查询只返回一行
$row = mysqli_fetch_assoc();
return $row;
然后调用方执行以下操作:
$row = get_quotes();
if ($row) {
echo $row['quote_text'];
echo $row['quote_author'];
}
你应该这样做:
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'];
返回['text'=>$row['quote\u text'],'author'=>$row['quote\u author']]
如果将查询限制为一个结果,为什么需要while
循环?在访问它的索引之前,您不需要检查$row
是否为空吗?@ciriusrob-Sure,但这不是一项要求。我还要检查连接错误。谢谢你,老兄!你太棒了。