gpt4 book ai didi

php - 将 php 函数中的 SQL 结果保存为数组

转载 作者:行者123 更新时间:2023-11-29 06:20:45 25 4
gpt4 key购买 nike

所以我主要是尝试通过 php 函数从 SQL 中获取 quote_author 和 quote_text 结果,然后以程式化的 html 显示它。当我调用该函数时,我想获得 2 个变量 $quote_text 和 $quote_author,因此我可以将它们放在 html 中的两个单独的 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'];

提前致谢!

最佳答案

您应该使用return 语句来返回函数的结果。您也不需要 while 循环,因为查询只返回一行。

$row = mysqli_fetch_assoc();
return $row;

然后调用者做:

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

关于php - 将 php 函数中的 SQL 结果保存为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33421461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com