我想对Mysql查询使用带有while循环的'return'函数,但它仅返回一个结果。
我的数据库中有这个:
id name author
1 foo fooo
2 foo2 fooo2
它仅返回“ 2”,但我想要“ 1”,“ 2”,“ 3”等。
这是我的代码:
function get_thm_cat() {
require 'database.php';
$req = $bdd->prepare("SELECT * FROM sk_cat ORDER BY id ASC");
$req->execute();
if ($req->rowCount() > 0) {
while ($row = $req->fetch()) {
return '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
}
$req->closeCursor();
}
使用return可以停止执行该函数,这意味着当PHP第一次遍历循环并到达时return
,它将立即返回到最初调用该函数的位置。$req->closeCursor();
因此,当结果多于0行时,不执行while循环的任何后续迭代,也不会执行对的调用。
依次返回多个字符串的最简单方法是创建一个临时变量,该变量在每次迭代时都填满并在循环后返回,如下所示:
$output = '';
while ($row = $req->fetch()) {
$output .= '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
return $output;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句