我正在使用一个简单的函数,当检查用户是否具有适当的帐户类型时返回true。
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;
}
}
函数名为userHasType,我现在这样使用这个函数:
$userHasType = userHasType('thisAccount');
.......
if ($userHasType AND whatever) {
我想使用一个语句,基本上,如果用户没有特定的类型,则会发生这种情况,否则会发生其他情况
:
if (!$userHasType AND whatever) {
或者我猜这实际上是可行的:
$userNotHasType = !userHasType('thisAccount');
.......
if ($userNotHasType AND whatever) {
无论哪种方式,什么是正确的方式去做这件事…因为我两种都试过了,但由于某种原因,它的反应不像我期望的那样。这可能是由于其他原因,但我的结论是,这两种方法都不可能奏效。
因此,如果能把这件事弄清楚,我将不胜感激。
编辑:谢谢! !
if (!$userHasType) {
$prPrice = ($prPrice2 != 0 && $userIsLoggedIn ) ? $prPrice2 : $prPrice1;
} else {
$prPrice = ($prPrice2 != 0 && $userIsLoggedIn ) ? $prPrice2Incl2PIncl : $prPrice1Incl2PIncl;
}
是的,你可以使用!操作符,你将得到函数调用返回值的布尔值的负值,你也可以对变量做同样的事情。
看看你的函数代码,在我看来是那种类型。Id可以是整数,而不是字符串类型的值,如varchar或文本。数据库在types表中显示的列id的类型是什么?
正如Polynomial所提到的,我建议您避免使用AND
。在处理正常的优先级情况时,&&
通常是更好的选择。
关于变量的使用;我认为在合理的情况下尽量减少额外变量的使用是一种很好的做法。当然,在我看来,这个决定取决于变量的使用量。我建议使用:
if (!$userHasType && whatever) {
或者如果你不在其他地方使用$userHasType
,那么就直接使用内联函数调用:
if (!userHasType('thisAccount') && whatever) {