php if statment for showing certain blocks of html
I am currently trying to check my db table to see if a user's level is开发者_如何学Go equal to or less than 10, if so then show an entire html list, if not and is equal or less than 5 show only the remaining part of the list. Here's where I started:
<?php
$levels = mysql_query("SELECT level FROM users");
if ($levels <= 10) {
?>
html list
<?php
if ($levels <= 5)
?>
html list
<?php
}
?>
I am trying to wrap my head around it, I just can't seem to get it.
Try this:
<?php if ($levels <= 5): ?>
html list
<?php elseif ($levels <= 10): ?>
html list
<?php endif; ?>
As David Fells said, make sure you are getting a result first :)
EDIT: I misread your question I think. Try this instead:
<?php if ($levels <= 10): /* If equal to or less than 10 */ ?>
<?php if ($levels > 5): /* if greater than 5 */ ?>
first part of html list
<?php endif; ?>
second part of html list
<?php endif; ?>
I was confused by this:
if a user's level is equal to or less than 10, if so then show an entire html list, if not and is equal or less than 5 show only the remaining part of the list
..as 0-5 will be less or equal to ten. Please excuse the mixup, GL!
$result = mysql_query(sprintf("SELECT level FROM users WHERE user_id = %d", $current_user_id));
if (list($level) = mysql_fetch_array($result)) {
if ($level <= 5) {
// whatever
}
elseif ($level <= 10) {
// whatever
}
else {
// whatever
}
}
Does that clear it up at all? You need to supply the ID of the current user, and then you need to actually retrieve the value from the $result. The $result is a variable of type resource, and you have to work on it with functions designed to do so.
You need to ask for the levels <= 5 before levels <= 10, because levels <= 10 will always find levels <= 5.
The code has lots of bugs-
Firstly,
$levels = mysql_query("SELECT level FROM users");
returns an array with levels of all the users. You want to query specific user's level using WHERE clause.
Next , when you want to differentiate between <=5 and btween 5 &10, u need to use either of the methods
if($levels>5 && $levels <=10){
`enter code here`
}elseif($levels<=5){
`enter code here`
}
Or
if($levels<=5){
`enter code here`
}elseif($levels<=10){
`enter code here`
}
I prefer the second one in this case as it involves one less comparison.
Next, you look like just beginning out in PHP. You did not close the braces and did not use else statements.
精彩评论