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