I am fetching data from MYSQL database and Looping through the result but its returning only one row !!! can any one explain what's wrong
我正在从MYSQL数据库获取数据,并循环遍历结果,但它只返回一行!!!谁能解释一下是怎么回事?
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
return $row;
}
}
}
2 个解决方案
#1
4
The return should be outside the while loop !
返回应该在while循环之外!
Here is how you can get all the rows :
下面是如何得到所有的行:
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
$arr = array();
while($row = $stmt->fetch_row())
{
$arr[] = $row;
}
return $arr;
}
}
Or you can do something like this return a generator and loop through :
或者你可以像这样返回一个生成器然后循环:
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
yield $row;
}
}
}
see the result here !
看到结果了!
echo '<pre>';
foreach (getAll() as $value) {
print_r($value);
}
#2
0
Once you hit a return statement all execution of that function stops. You cannot return multiple times.
一旦你点击返回语句,所有函数的执行都会停止。您不能多次返回。
You can either return an array of all rows:
您可以返回所有行的数组:
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0) {
while($row = $stmt->fetch_row())
{
$array[] = $row;
}
return $array;
}
}
Or use it as a generator (probably not what you want):
或者使用它作为生成器(可能不是你想要的):
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
yield $row;
}
}
}
#1
4
The return should be outside the while loop !
返回应该在while循环之外!
Here is how you can get all the rows :
下面是如何得到所有的行:
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
$arr = array();
while($row = $stmt->fetch_row())
{
$arr[] = $row;
}
return $arr;
}
}
Or you can do something like this return a generator and loop through :
或者你可以像这样返回一个生成器然后循环:
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
yield $row;
}
}
}
see the result here !
看到结果了!
echo '<pre>';
foreach (getAll() as $value) {
print_r($value);
}
#2
0
Once you hit a return statement all execution of that function stops. You cannot return multiple times.
一旦你点击返回语句,所有函数的执行都会停止。您不能多次返回。
You can either return an array of all rows:
您可以返回所有行的数组:
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0) {
while($row = $stmt->fetch_row())
{
$array[] = $row;
}
return $array;
}
}
Or use it as a generator (probably not what you want):
或者使用它作为生成器(可能不是你想要的):
function getAll()
{
global $con;
$SQL = "SELECT * FROM users";
$stmt = $con->query($SQL);
if($stmt->num_rows > 0){
while($row = $stmt->fetch_row())
{
yield $row;
}
}
}