使用 PDO 循环和函数 return
While loop and function return with PDO
我想对我的 Mysql 查询使用带有 while 循环的 'return' 函数,但它 returns 只有一个结果。
我的数据库中有这个:
id name author
1 foo fooo
2 foo2 fooo2
它returns只有“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
是结束函数并从中断处继续处理代码的命令。您应该将结果存储在 while
循环和 return 保存这些结果的数组中,或者您应该 echo
在 while
循环中的结果。
while ($row = $req->fetch_assoc() ) {
echo '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
或
$results = array();
while ($row = $req->fetch_assoc() ) {
$results[] = '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
return $results;
使用return你停止函数的执行,这意味着当PHP第一次遍历你的循环并到达return
时,它立即回到哪里您最初调用了该函数。因此,当结果超过 0 行时,while 循环的任何后续迭代都不会执行,并且您对 $req->closeCursor();
的调用也不会执行。
return 多个字符串的最简单方法是创建一个临时变量,您在每次迭代时填充该变量并在循环后 return,如下所示:
$output = '';
while ($row = $req->fetch()) {
$output .= '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
return $output;
我想对我的 Mysql 查询使用带有 while 循环的 'return' 函数,但它 returns 只有一个结果。
我的数据库中有这个:
id name author
1 foo fooo
2 foo2 fooo2
它returns只有“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
是结束函数并从中断处继续处理代码的命令。您应该将结果存储在 while
循环和 return 保存这些结果的数组中,或者您应该 echo
在 while
循环中的结果。
while ($row = $req->fetch_assoc() ) {
echo '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
或
$results = array();
while ($row = $req->fetch_assoc() ) {
$results[] = '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
return $results;
使用return你停止函数的执行,这意味着当PHP第一次遍历你的循环并到达return
时,它立即回到哪里您最初调用了该函数。因此,当结果超过 0 行时,while 循环的任何后续迭代都不会执行,并且您对 $req->closeCursor();
的调用也不会执行。
return 多个字符串的最简单方法是创建一个临时变量,您在每次迭代时填充该变量并在循环后 return,如下所示:
$output = '';
while ($row = $req->fetch()) {
$output .= '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
return $output;