Php函数从MYSQL生成多个返回

时间:2018-04-18 12:17:20

标签: php

function get_limit_markets(){
 $count_nodes=querydb("SELECT id,market,mkt from  markets where status= 1 
 order by market asc limit 5 ");
  $result=mysqli_fetch_array($count_nodes,MYSQLI_ASSOC);
  return  array('market' => $result['market'] ,
            'mkt' => $result['mkt'],
            'id' => $result['id'] 
        );
   }


$res=get_limit_markets();
extract($res);

我想创建一个函数来查询表市场并获取行id,market,mkt。 然后我将调用该方法是单独的文件并在我的表下

<table class="table table-hover mb-0">
    <thead>
        <tr>
            <th>Market</th>
            <th>Abbreviation</th>
            <th>Environments</th>
            <th>Endpoints</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody>
     <?php //while loop and call function to generate new row for eachc?>

2 个答案:

答案 0 :(得分:2)

你需要在函数

中返回整个$result;而不是你创建的数组
function get_limit_markets(){
    $count_nodes=querydb("SELECT id,market,mkt from  markets where status= 1 
    order by market asc limit 5 ");
    $result=mysqli_fetch_all($count_nodes,MYSQLI_ASSOC); // use _all to get all records
    return  $result;
}

现在应用foreach()获取所有记录并将其显示在表格中。

所以a.php如下所示: -

<table class="table table-hover mb-0">
    <thead>
        <tr>
            <th>Market</th>
            <th>Abbreviation</th>
            <th>Environments</th>
            <th>Endpoints</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody>
         <?php 
         $res=get_limit_markets();
         foreach($res as $re){?>
             <tr>
                <td><?php echo $re['id'];?></td>
                <td><?php echo $re['market'];?></td>
                <td><?php echo $re['mkt'];?></td>
                <td>Endpoints</td>
                <td>1</td>

             </tr>


        <?php }?>

    </tbody>
</table>

答案 1 :(得分:1)

该函数需要从查询中获取所有行 - mysqli_fetch_array()仅检索一行。另一方面,mysqli_fetch_all()返回查询中的所有行...

function get_limit_markets(){
    $count_nodes=querydb("SELECT id,market,mkt 
                           from  markets 
                           where status= 1 
                           order by market asc 
                           limit 5 ");

    return mysqli_fetch_all($count_nodes,MYSQLI_ASSOC);
}

$res=get_limit_markets();
print_r($res);

这将为您提供一个包含每条记录行的数组。您可以使用foreach()或您需要的任何其他方法循环它。