I’m using Mysqli OO to search the database for 2 specific values using the MySQL statement CASE. If both values are found then it will return the value ‘true’, if only one is found the value is ‘false’, if neither are found then the result is neither. Anyway I’ve got this working but my problem is I need it to also display the values that are related in the column.
$query = "SELECT 'userName','email','code',
CASE
WHEN (email=? AND code=?) THEN 'true'
WHEN (email=?) THEN 'false'
ELSE 'NONE'
END AS answer
FROM users WHERE email=?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ssss", $email,$code, $email,$email);
$email = $mysqli->real_escape_string($email);
$code = $mysqli->real_escape_string($code);
$stmt->execute();
$stmt->bind_result($user,$email,$code,$answer);
$stmt->fetch();
print_r($stmt->fetch);
$stmt->store_result();
echo "User: ".$user." Email: ".$email." Code: ".$code." Answer: ".$answer;
Okay so when I run the code it should display as:
User: ryan Email: local@localhost Code: 12 Answer: true
But instead it displays it as:
User: userName Email: email Code: code Answer: true
So I think the error is more to do with the SQL side of it, but I’m stuck and would like some help. Thanks
You are selecting string literals such as
'userName'rather than the values contained in the columns.To solve the problem either remove the quotes round your column names:
Or use backticks (allowed, but only required if the column name is a reserved word):