douwen7905 2012-08-26 14:43
浏览 100
已采纳

如何使用PHP从foreach循环返回多个值

Here's my function

function GetUser($id)
{
    global $pdo;
    $stmt = $pdo->prepare('SELECT lname,fname,mi FROM user WHERE id = :id LIMIT 1');
    $stmt->execute(array(':id'=>$id));
    foreach($stmt as $name){
        $lname = $name['lname'];
        $lname = $name['fname'];
        $mi = $name['mi'];
    }

    return //what to put here?
}

Here's my code to use the function

include 'function.php';
$names = GetUser($_SESSION['id']);
//what's next?

How can i retrieve the $lname,$fname and $mi from the function? Need any help and suggestions. Thank you :)

  • 写回答

5条回答 默认 最新

  • doujianqin5172 2012-08-26 14:47
    关注

    For starters don't use the global keyword, but inject the variable you need. Second why don't you return an array?:

    function getUser($pdo, $id)
    {
        $stmt = $pdo->prepare('SELECT lname,fname,mi FROM user WHERE id = :id LIMIT 1');
        $stmt->execute(array(':id'=>$id));
    
        $result = array();
        foreach($stmt as $name){
            $result['lname'] = $name['lname'];
            $result['fname'] = $name['fname'];
            $result['mi']  = $name['mi'];
        }
    
        return $result;
    }
    
    $result = getUser($pdo, 1);
    var_dump($result);
    

    Note that this will only return the last result. If you want it all:

    function getUser($pdo, $id)
    {
        $stmt = $pdo->prepare('SELECT lname,fname,mi FROM user WHERE id = :id LIMIT 1');
        $stmt->execute(array(':id'=>$id));
    
        return $stmt->fetchAll();
    }
    
    $result = getUser($pdo, 1);
    var_dump($result);
    

    Also note that I have made your function name starting with a normal letter instead of a capital. The "normal" naming convention is that classes start with a capital, but function / methods with a normal one.

    If you want to retrieve the information based on the first solution you would do:

    echo $result['lname'];
    

    If you want to retrieve the information based on the second solution you would do:

    echo $result[0]['lname'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用