我有一个函数应该根据他的 ID 号给我一个工作人员的名字,所以我的 php 是这样的
$staffId = $_GET['staff_id'];
$staff = staff_load($staffId);
我的功能是这样的
function staff_load()
{
$dbh = dbh_get(); //connects to database
$sql = 'select user_name from user_staff where user_id = ?';
$stmt = $dbh->prepare($sql);
$stmt->execute();
$staff = $stmt->fetch();
dbh_free($dbh); //disconnects from database
return $staff;
}
但是当我尝试使用 $staff 变量时,它什么也没显示。我不知道我做错了什么。我尝试了很多变体,除了沮丧之外一无所获。
<td>Book for ' . $staff . '</td>
最佳答案
首先,您忘记在函数定义中包含参数:
function staff_load($id) {
然后需要绑定(bind)prepared statement的参数。
$sql = 'select user_name from user_staff where user_id = $1';
$stmt = $dbh->prepare($sql);
$stmt->execute(array($id));
接下来,fetch()
返回一个数组,需要从数组中提取user_name
元素:
$row = $stmt->fetch();
if ($row) {
$staff = $row['user_name'];
} else {
$staff = false;
}
关于php - 在 php 函数返回值中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41802792/