I'm trying to use prepared statements to retrieve user information from my DB. I want to be able to retrieve this information based one one of multiple columns (id, user_name, activation_token). But, I'm running into an error when I try to define which column to use. Here's the code:
//Retrieve complete user information by username, token or ID
function fetchUserDetails($username=NULL,$token=NULL, $id=NULL)
{
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("SELECT
id,
user_name,
display_name,
password,
email,
activation_token,
last_activation_request,
lost_password_request,
active,
title,
sign_up_stamp,
last_sign_in_stamp
FROM ".$db_table_prefix."users
WHERE
? = ?
LIMIT 1");
if($username!=NULL) {
$stmt->bind_param("ss", "user_name", $username);
}
elseif($token!=NULL) {
$column = "activation_token";
$stmt->bind_param("ss", $column, $token);
}
elseif($id!=NULL) {
$column = "id";
$stmt->bind_param("ss", $column, $id);
}
$stmt->execute();
$stmt->bind_result($id, $user, $display, $password, $email, $token, $activationRequest, $passwordRequest, $active, $title, $signUp, $signIn);
while ($stmt->fetch()){
$row = array('id' => $id, 'user_name' => $user, 'display_name' => $display, 'password' => $password, 'email' => $email, 'activation_token' => $token, 'last_activation_request' => $activationRequest, 'lost_password_request' => $passwordRequest, 'active' => $active, 'title' => $title, 'sign_up_stamp' => $signUp, 'last_sign_in_stamp' => $signIn);
}
$stmt->close();
return ($row);
}
As you can see, I'm trying two different methods here. In username, trying to bind the first parameter as a string. When I do this, I get the error:
Fatal error: Cannot pass parameter 2 by reference
In the second case, I'm assigning the column name "activation_token" to a variable, and then using that variable to bind the first paramete. When I do this, I get the error:
Notice: Undefined variable: row
As if there's no information in the DB with the token I'm defining, so it couldn't retrieve it... but there definitely is data there.
Any help would be appreciated 🙂