Php 而循环和函数使用PDO返回
我想在Mysql查询中使用带有while循环的“return”函数,但它只返回一个结果Php 而循环和函数使用PDO返回,php,mysql,pdo,Php,Mysql,Pdo,我想在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"
我的数据库中有:
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();
}
函数get\u thm\u cat(){
需要“database.php”;
$req=$bdd->prepare(“根据id ASC从SKU cat订单中选择*);
$req->execute();
如果($req->rowCount()>0){
而($row=$req->fetch()){
返回“- .”行[“id”]。“Name=”。$row[“Name”]。
;
}
}
$req->closeCursor();
}
return
是一个命令,用于结束函数并继续处理停止的代码。您应该将结果存储在while
循环中并返回保存这些结果的数组,或者应该echo
将结果存储在while
循环中
while ($row = $req->fetch_assoc() ) {
echo '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
while($row=$req->fetch_assoc()){
echo'- 。$row[“id”]。'Name='。$row[“Name”]。
;
}
或
$results=array();
而($row=$req->fetch_assoc()){
$results[]='- .$row[“id”]。'Name='.$row[“Name”]。
;
}
返回$results;
停止函数的执行,这意味着当PHP第一次迭代循环并到达返回时,它会立即返回到最初调用函数的位置。while循环的任何后续迭代都不会执行,您对$req->closeCursor()的调用也不会执行因此,当结果超过0行时,也不会执行代码>
要在每个字符串之后返回多个字符串,最简单的方法是创建一个临时变量,在每次迭代时填充该变量,然后在循环后返回,如下所示:
$output = '';
while ($row = $req->fetch()) {
$output .= '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
return $output;
$output='';
而($row=$req->fetch()){
$output.='- .$row[“id”]。'Name='.$row[“Name”]。
;
}
返回$output;
调整了代码。在第二种方法中,您必须添加代码以输出$results
的元素。创建一个数组,在while
循环中将行推送到数组中。最后返回函数中的数组和while
循环之外的数组。
$output = '';
while ($row = $req->fetch()) {
$output .= '<ul id="ul_cat"><li id="li_cat">'.$row["id"].' Name = '.$row["name"].'<br>';
}
return $output;