duandan4680
duandan4680
2017-01-23 09:22

在php函数中使用变量返回值

已采纳

I have a function that is supposed to give me a staff members name from his ID number so my php is like this

$staffId = $_GET['staff_id'];
$staff = staff_load($staffId);

and my function is like this

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;
}

But when I try and use the $staff variable, it shows nothing. I can't work out what I'm doing wrong. I've tried a bunch of variants and gotten nowhere except frustrated.

<td>Book for ' . $staff . '</td>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doudi4621 doudi4621 4年前

    First, you forgot to include the parameter in your function definition:

    function staff_load($id) {
    

    Then you need to bind the parameter of the prepared statement.

    $sql = 'select user_name from user_staff where user_id = $1';
    $stmt = $dbh->prepare($sql);
    $stmt->execute(array($id));
    

    Next, fetch() returns an array, you need to extract the user_name element from the array:

    $row = $stmt->fetch();
    if ($row) {
        $staff = $row['user_name'];
    } else {
        $staff = false;
    }
    
    点赞 评论 复制链接分享
  • douwo8358 douwo8358 4年前

    first of all you have to pass parameter to staff_load function

    function staff_load($staffId)
    

    secondly you should bind parameter

    $sql = 'select user_name from user_staff where user_id = :user_id';
    $stmt = $dbh->prepare($sql);
    $stmt->bindParam(':user_id', $staffId);
    
    点赞 评论 复制链接分享