在函数中获取数据

Fetch data in a function

所以我试图在我站点的多个位置(PDO)函数中获取我的数据,并且不想在函数中回显行。似乎无法正常工作。

我的函数

function getUser(){
global $db;
$userId = $_SESSION['userId'];
$sql = "SELECT firstName FROM users WHERE userId = $userId";
$stmt = $db->prepare($sql);
$stmt->execute();

$row = $stmt->fetch();

//the problem
echo $row['firstName'];

}

我如何调用函数

<?php
    getUser();
?>

我不想在函数中回显 $row['firstname'],但是在我想使用它的网站上?

希望它有意义?

谢谢

而不是回应它:

//the problem
echo $row['firstName'];

就return它

return $row['firstName'];

然后调用的时候可以这样:

<?php
    $user = getUser();
    echo "$user<br />\n";
?>

如果您需要 return 多列,您可以这样做:

return array($row['col1'], $row['col2']);

然后像这样在另一端分配它:

list($col1, $col2) = getXyz($someID);