I am working with a simple function that returns true when checking if a user has an appropriate account type.
function userHasType($type)
{
include $_SERVER['DOCUMENT_ROOT'] . '/pathTo/db.connection.php';
$accNum = mysqli_real_escape_string($link, $_SESSION['accountNum']);
$type = mysqli_real_escape_string($link, $type);
$sql = "SELECT COUNT(*) FROM users
INNER JOIN user_types ON users.id = userId
INNER JOIN types ON typeId = types.id
WHERE users.id = '$accNum' AND types.id='$type'";
$result = mysqli_query($link, $sql);
if (!$result)
{
$error = 'Error searching for user types.';
include 'error.html.php';
exit();
}
$row = mysqli_fetch_array($result);
if ($row[0] > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
The function is named userHasType, i currently use this function like this:
$userHasType = userHasType('thisAccount');
.......
if ($userHasType AND whatever) {
I would like to use a statement where basically, if the user does not have a specific type, then this will happen, else something else will happen.
As in:
if (!$userHasType AND whatever) {
or im guessing this would actually work:
$userNotHasType = !userHasType('thisAccount');
.......
if ($userNotHasType AND whatever) {
Which ever way though, what is the right way to go about this… Because I have tried both and for some reason it is not reacting the way i would expect it to. It would be due to something else, but my conclusion is that both these ways must not work.
So some clarity on the matter would be much appreciated.
EDIT:
Thank You!!
if (!$userHasType) {
$prPrice = ($prPrice2 != 0 && $userIsLoggedIn ) ? $prPrice2 : $prPrice1;
} else {
$prPrice = ($prPrice2 != 0 && $userIsLoggedIn ) ? $prPrice2Incl2PIncl : $prPrice1Incl2PIncl;
}
Yes you CAN use the ! operator in front of a function call and you will get the boolean negative of the function call’s return value, and you can do the same to a variable.
Looking at your function code, it seems to me that type.id might be an integer, rather than a string-type value such as a varchar or text. What does the database show as the type for the column id in the types table?
As mentioned by Polynomial, I suggest you avoid using
AND.&&is usually a better choice when you are dealing with normal precedence situations.About the use of variables; I think it is good practice to minimize the use of extra variables when reasonable. Of course IMHO this decision is subject to the amount of use the variable has. I suggest sticking with:
or if you do not use
$userHasTypeanywhere else then just go ahead and use the function call in-line: