我正在尝试制作基于排名的导航系统。因此,用户的排名越高,他获得的导航选项就越多。我做了:
$rank = "SELECT rank FROM users WHERE username = '".$_SESSION['username']."'";
然后我尝试了:
if ($rank > 5) {
// show rank 5 navigation
} else {
// show lower than rank 5 navigation
}
但它对我不起作用..
有什么想法吗?
答案 0 :(得分:1)
以下示例应足以让您开始正确的路径。
查看PHP Prepared Statements,了解有关从MySQL中提取信息的最佳方法的详细信息。
另外,看看MySQL的Comparison Functions and Operators和PHP的比较运算符。
<?php
// Place everything in a function to keep it somewhat organized.
function displaySpecialUserMenu($username){
// Connect to database
$db = new PDO('mysql:host=localhost;dbname=testDatabaseName', 'testDatabaseUser', 'testPassword123');
// Turn on error mode. Turn this OFF for production.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Select statement should return "1" if a user's rank is above 5
$statement = $db->prepare('SELECT EXISTS(SELECT 1 FROM users WHERE rank > 5 AND username = :username');
// Prepare the variables for the statement.
$statement->bindParam(':username', $username, PDO::PARAM_STR);
// Run the prepared statement
$statement->execute();
// Store the result (It'll be either a 0 or a 1) in $result
$result = $statement->fetchColumn();
if($result>0){
// User's rank is greater than 5
// Display menu here
echo '[high_rank_menu_here]';
}else{
// User's rank is greater than 5
// Display menu here
echo '[low_rank_menu_here]';
}
}
// Place this line where you want your menu to display.
displaySpecialUserMenu($_SESSION['username']);
?>
您也可以使用PHP而不是MySQL来执行逻辑,如上例所示。
<?php
function displaySpecialUserMenu($username){
// Connect to database
$db = new PDO('mysql:host=localhost;dbname=testDatabaseName', 'testDatabaseUser', 'testPassword123');
// Turn on error mode. Turn this OFF for production.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Select rank from user
$statement = $db->prepare("SELECT rank FROM users WHERE username = :username");
// Prepare the variables for the statement.
$statement->bindParam(':username', $username, PDO::PARAM_STR);
// Run the prepared statement
$statement->execute();
// Store the result
$rank = $statement->fetchColumn();
if($rank>5){
// User's rank is greater than 5
// Display menu here
echo '[high_rank_menu_here]';
}else{
// User's rank is greater than 5
// Display menu here
echo '[low_rank_menu_here]';
}
}
// Place this line where you want your menu to display.
displaySpecialUserMenu($_SESSION['username']);
?>