2017-01-23 09:22
浏览 46


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);
$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>

图片转代码服务由CSDN问答提供 功能建议


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


  function staff_load()
 $ dbh = dbh_get();  //连接到数据库
 $ sql ='从user_staff中选择user_name,其中user_id =?'; 
 $ stmt = $ dbh-&gt; prepare($ sql); 
 $ stmt-&gt; execute();  
 $ staff = $ stmt-&gt; fetch(); 
dbh_free($ dbh);  //断开与数据库
return $ staff; 

但是当我尝试使用$ staff变量时,它什么也没显示。 我无法弄清楚我做错了什么。 我已经尝试了一堆变种,除了受挫之外没有任何变化。

 &lt; td&gt; Book for'。  $ staff。  '&lt; / td&gt; 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doudi4621 2017-01-23 09:29

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

    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 2017-01-23 09:27

    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);
    解决 无用
    打赏 举报

相关推荐 更多相似问题