Showing different content based on $_SESSION UserLevel - php

I am having a problem with trying to show different menu options based on UserLevel. I have a mysql database with a users table. The users table contains a UserLevel which will either be set to 0 or 1. But for some reason my php just isn't working. In fact, when I add the php to the menu, it then does not display ANYTHING on the site below the menu. Any advice would be much appreciated.
Code that starts session
<?php
if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username']))
{
?>
<?php include "mainNav.php"; ?>
<center>
<h2> Campaign Updates</h2>
</center>
<div id="campaignPostWrap">
<div id="campaignScrollBox">
<?php
$con=mysqli_connect("localhost","dorians","ds2953!b67P$","aldentec");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM campaigns ORDER BY postDate desc");
while($row = mysqli_fetch_array($result))
{
echo "<div id='campaignPostContainer'>";
echo "<ul class='campaignPostBox'>";
echo "<p class='postInfo'>";
echo "Posted on:";
echo "<li>" . $row['postDate'] . "</li>";
echo "</p>";
echo "<p class='postInfo'>";
echo "Posted by:";
echo "<li>" . $row['postName'] . "</li>";
echo "</p>";
echo "<li class='postEntry'>" . $row['postEntry'] . "</li>";
echo "</ul>";
echo "</div>";
echo "<hr>";
}
mysqli_close($con);
?>
</div>
<?php include "campaignPost.php"; ?>
</div>
<?php include "chat.php"; ?>
<?php
}
elseif(!empty($_POST['username']) && !empty($_POST['password']))
{
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$checklogin = mysql_query("SELECT * FROM users WHERE Username = '".$username."' AND Password = '".$password."'");
if(mysql_num_rows($checklogin) == 1)
{
$row = mysql_fetch_array($checklogin);
$email = $row['EmailAddress'];
$userlevel = $row['UserLevel'];
$_SESSION['Username'] = $username;
$_SESSION['EmailAddress'] = $email;
$_SESSION['LoggedIn'] = 1;
$_SESSION['UserLevel'] = $userlevel;
echo "<h1>Success</h1>";
echo "<p>We are now redirecting you to the member area. If you are not automatically redirected <a href='index.php'>Click here</a></p>";
header( "refresh:10;url=index.php" );
}
else
{
echo "<h1>Error</h1>";
echo "<p>Sorry, your account could not be found. Please click here to try again.</p>";
}
}
else
{
?>
Menu code that isn't working
<?php session_start(); ?>
<?php
$userlevel = $_SESSION['UserLevel'];
if($userlevel == 0) {
echo "<ul class="mainNav">
<li> Create Character</li>
<li> Create Quest</li>
<li> View Characters</li>
<li> View Quests</li>
<li> Book List</li>
</ul>";
} elseif($userlevel == 1) {
echo "<li> DM Tools</li>";
}
?>
<?php include "greeter.php"; ?>

Your quotes are undoubtedly the problem here:
if($userlevel == 0) {
echo "<ul class="mainNav">
<li> Create Character</li>
<li> Create Quest</li>
<li> View Characters</li>
<li> View Quests</li>
<li> Book List</li>
</ul>";
} elseif($userlevel == 1) {
echo "<li> DM Tools</li>";
}
Notice the syntax highlighting above shows the issue in your string. See how it turns black when it gets to mainNav? That's because mainNav is no longer part of the string. That's a bad thing here.
Look at the first line of your echo:
echo "<ul class="mainNav">
You open a quote and then close it at class=". Now, it's trying to evaluate mainNav as a constant or some other language construct. On top of that, it doesn't know what to do with mainNav as you haven't provided any kind of operators.
Instead, you should do something like:
if($userlevel == 0) {
echo '<ul class="mainNav">
<li> Create Character</li>
<li> Create Quest</li>
<li> View Characters</li>
<li> View Quests</li>
<li> Book List</li>
</ul>';
} elseif($userlevel == 1) {
echo '<li> DM Tools</li>';
}
Alternatively, you could escape every location where there is a non-string-terminating quote like \".
Another option would be to use Heredoc syntax.

Related

Trying to see if username is in the database once I'm logged in?

I went through multiple processes of trying to accomplish this, but couldn't quite figure it out. I went on Stack Overflow to find duplicate answers. I found some and try to adjust them into my code. Still no use. I'm trying to say if I'm logged in go to the profile page and if a username is in the database, I want you to display their name. If not in the database, then just don't show anything. Here is what I came up with:
if (isset($_SESSION['user_id'])){
$username = mysqli_real_escape_string($con, $_POST['username']);
$sql = "SELECT * FROM users WHERE username = '".$username."'";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result)>=1){
echo "User was found in the database";
}
else{
echo "User was not found in the database.";
}
}
So the if isset user_id basically says if I'm logged in then do this. The code after that is trying to find if a username is found in that database. If so then say it's found. If not, then don't. I hope this was clear! Thank you!
EDIT: Here is the HTML Code:
<?php
session_start();
ob_start();
include_once('dbconnect.php');
?>
<div class="banner_container">
<div class="jumbotron text-center">
<?php
if (isset($_SESSION['user_id']) && isset($_POST['username'])){
if(($_SESSION['user_id'] != "") && ($_POST['username'] != "")){
$user_id = $_SESSION['user_id'];
$username = mysqli_real_escape_string($con, $_POST['username']);
$sql = "SELECT * FROM users WHERE username = '".$username."' AND user_id !=".$user_id;
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0){
echo "User was found in the database";
}
else{
echo "User was not found in the database.";
}
}
else{
echo "Username or user Id is empty";
}
}
?>
<?php
echo "<h1>";
echo $_SESSION['first_name'];
echo " ";
echo $_SESSION['last_name'];
echo "</h1>";
echo "<p>";
echo '"';
echo $_SESSION['quote'];
echo '"';
echo "<br>";
echo $_SESSION['who'];
echo "</p>";
?>
</div>
</div>
<li>Home</li>
<li> About</li>
<li class="qotd"> Quote of the Day</li>
<li class="all_categories">All Categories</li>
<li> Authors</li>
<?php
if(isset($_SESSION['user_id'])){
echo $_SESSION['user_id'];
echo '<li id="active" class="dropdown">';
echo '<a id="act_color" href="#" class="dropdown-toggle" data-toggle="dropdown">';
echo $_SESSION['first_name'];
echo "'s";
echo ' ';
echo "Profile";
echo '<b class ="caret"></b></a>';
echo '<ul class="dropdown-menu">';
echo '<li> Profile</li>';
echo '<li>Log out</li>';
echo '</ul>';
echo '</li>';
echo '</a>';
echo '</li>';
} else {
}
?>
This is the profile page that I'm on.
Use this code:
if (isset($_SESSION['user_id']) && isset($_POST['username'])){
if(($_SESSION['user_id'] != "") && ($_POST['username'] != "")){
$user_id = $_SESSION['user_id'];
$username = mysqli_real_escape_string($con, $_POST['username']);
$sql = "SELECT * FROM users WHERE username = '".$username."' AND user_id !=".$user_id;
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0){
echo "User was found in the database";
}
else{
echo "User was not found in the database.";
}
}
else{
echo "Username or user Id is empty";
}
}

Don't show pagination if only one page is returned (Php)

I have a simple and working php pagination. If only one page is returned, the pagination still shows up with a link to page one. How do I hide or remove this link of no use when only one page is returned? Any help much appreciated…
My code is like this:
<?php
include 'config.php';
include 'opendb.php';
?>
<?php
$row=$conn;
mysql_select_db('DB_NAME',$row);
$start=0;
$limit=12;
if(isset($_GET['id']))
{
$id=$_GET['id'];
$start=($id-1)*$limit;
}
$query=mysql_query("SELECT * FROM `table` LIMIT $start, $limit");
while($row=mysql_fetch_array($query))
{
?>
<!-- RESULT FROM DB -->
<? } ?>
<?php
$rows=$conn;
mysql_select_db('DB_NAME',$rows);
$rows=mysql_num_rows(mysql_query("SELECT * FROM `table`"));
$total=ceil($rows/$limit);
for($i=1;$i<=$total;$i++)
{
if($i==$id) {
?>
<li class='active'><a href='#'><?php echo "$i"; ?></a></li>
<?php } else { ?>
<li><a href='<?php echo "?id=$i"; ?>'><?php echo "$i"; ?></a></li>
<?php }
}
?>
//check if the qty is greater than one before running the for loop.
if( $total > 1 )
{
for($i=1;$i<=$total;$i++)
{
if($i==$id)
{
echo "<li class='active'><a href='#'>$i</a></li>";
}
else
{
echo "<li><a href='?id=$i'>$i</a></li>";
}
}
}
Just check the qty before running the loop.
Also your sql syntax is outdated: http://php.net/manual/en/function.mysql-query.php

Php foreach echo issue

I have this code which produces me a number which is equal to the number of id's i've got in my database of star rating system.
This code generates me a five star voting for each id i've got, but the problem is, it generates them all in a div, while i need them specifically in different div's. let's suppose i print out in a div information for each hostess i've got, i print out their photo and name with the following code:
$sql =" select * from hostess";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
echo "<div id='photo'>";
echo "<div id='picture'>";
echo "<div id='scotch'><img src='images/Scotch.png'></div>";
echo "<td> <img src=foto/photo1/".$row['photo'] . "></td>";
echo "</div>";
echo "<div id='text'>";
echo '<td>'. $row['first_name_en']." ". $row['family_name_en']."</td>";
echo "</div>";
echo "</div>";
echo "<div id='photo2'>";
echo "<div id='picture'>";
echo "<div id='notes'>";
echo '<form action="index.php" method="post" >';
echo "<label>Notes</label></br><textarea>".$row['courrent_occupation'] . "</textarea></br>";
echo '<input type="submit" value="edit" name="edit"></div>';
echo "</div>";
echo "<div id='notes'>";
echo "<label>profile</label></br><textarea>".$row['profile_en'] . "</textarea>";
echo "</div>";
echo "</div>";
}
?>
</div>
Now, i've got this other php which generates me all the star ratings for all hostess id's
<?php
// include update.php
include_once 'update.php';
// get all data from tabel
$arr_star = fetchStar();
?>
<?php
// start looping datas
foreach($arr_star as $star){ ?>
<h2>Star Rater - <?php echo $star['id'];?></h2>
<ul class='star-rating' id="star-rating-<?php echo $star['id'];?>">
<?php /* getRating($id) is to generate current rating */?>
<li class="current-rating" id="current-rating-<?php echo $star['id'];?>" style="width:<?php echo getRating($star['id'])?>%"><!-- will show current rating --></li>
<?php
/* we need to generate 'id' for star rating.. this 'id' will identify which data to execute */
/* we will pass it in ajax later */
?>
<span class="ratelinks" id="<?php echo $star['id'];?>">
<li>1</li>
<li>1.5</li>
<li>2</li>
<li>2.5</li>
<li>3</li>
<li>3.5</li>
<li>4</li>
<li>4.5</li>
<li>5</li>
</span>
</ul>
<?php } ?>
What i need is to assign each hostess profile i print their system rating.
I try to insert the foreach inside the first script but it then shows me just one profile, not all profiles.
The fetchstar() code is:
function fetchStar(){
$sql = "select * from `hostess`";
$result=#mysql_query($sql);
while($rs = #mysql_fetch_array($result,MYSQL_ASSOC)){
$arr_data[] = $rs;
}
return $arr_data;
}
First, you probably shouldn't use SELECT *. That aside I would combine the two queries you have to return a multidimensional array with MySQL and then use nested for each loops to echo out the data you want.
Someone answered a similar question for me here.
Looping through MySQL left join in php vs. 2 separate queries
$sql =" select * from hostess";
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query)) {
if ($lastID <> $row['id']) {
$lastID = $row['id'];
$hostess[$lastID] = array('id' => $row['id'],
'first_name_en' => $row['first_name_en'],
etc
'arr_star' => array() );
}
$hostess[$lastID]['arr_star'][] = array('star_id' => $row['star_id'] etc);
}
Then you would use nested for each statements
for each($row as $rows){
//echo your hostess information
for each ($arr_star as $star){
//echo your star rating information
}
}

Echo results of mysql query with php

I have this query
$people = "SELECT name FROM people";
$people = mysql_query($people) or die(mysql_error());
$row_people = mysql_fetch_assoc($people);
$totalRows_people = mysql_num_rows($people);
I can echo the results within a unordered list using a while loop like this
<ul>
<?php {do { ?>
<li><?php echo $row_people['name'];?></li>
<?php } while ($row_people = mysql_fetch_assoc($people));}?>
</ul>
But I can't used this as my html does not allow it.
<ul>
<li class="first">
Kate
<li>
<li class="second">
<img src="john.jpg" />John
<li>
<li class="third">
<span>Max</span>
<li>
</ul>
My question is how can echo the name that was retrieved from the database into the appropriate place within this html?
Thanks for your help.
Try this:
<?php
$people = "SELECT name FROM people";
$people = mysql_query($people) or die(mysql_error());
if(mysql_num_rows($people) > 0){
?>
<ul>
<?php
while ($row_people = mysql_fetch_assoc($people)){
?>
<li><?php echo htmlentities($row_people['name']);?></li>
<?php
}
?>
</ul>
<?php
}
?>
You'll just have to create a renderer for each "type" of user (assuming you have a type property on the user rows) or based on their attributes. For example, let's say you're going to have to filter based on the attributes:
<?php
function render_simple($person) {
return '' . $person['name'] . '';
}
function render_with_image($person) {
return '<img src="' . $person['image'] . '.jpg"/>' . $person['name'] . '';
}
function render_special($person) {
return '<span>' . $person['name'] . '</span>';
}
function render_person($person) {
if ($person['image']) {
return render_with_image($person);
}
if ($person['special']) {
return render_special($person);
}
return render_simple($person);
}
$i = 0;
while ($row_people = mysql_fetch_assoc($people)){ ?>
<li class="index<?php echo ++$i; ?>">
<?php echo render_person($person); ?>
</li>
<?php
}
?>
This should work, with the exception that instead of class names first, second, etc, you'll now have index1, index2, etc.

Display partial rows after the first row

I am trying to take the following rows
username | id | role
SELECT u.username, u.id, r.role FROM ".TBL_USERS." u
INNER JOIN ".TBL_ADMIN_ROLES." r ON r.userid = u.id
WHERE u.userlevel > 3
At the moment, I use the following code to get the results.
<?php
$q = $database->getAllAdmins();
while($row=mysql_fetch_assoc($q))
{
?>
<a class="main" href="profile.php?id=<? echo $row['id']; ?>"><? echo $row['username']; ?></a>
<ul>
<li><? echo $row['role']; ?></li>
</ul>
<?
}
?>
Obviously, this is looping through and showing the username over and over.
What I want it to do is show the username once and then show every role below.
Any ideas? Thanks :)
$q = $database->getAllAdmins();
$user = "";
while($row=mysql_fetch_assoc($q)) {
if ($user != $row['username']) {
if ($user != "") { echo "</ul>"; }
echo "<a class='main' href='profile.php?id={$row['id']}'>{$row['username']}</a>";
echo "<ul>";
}
echo "<li>{$row['role']}</li>";
$user = $row['username'];
}
My answer is the same concept as the others, just cleaner.
If you add a ORDER BY i.id to your query, you can then use a variable to keep track of the last user.
<?php
$q = $database->getAllAdmins();
$lastUserID = 0;
while($row=mysql_fetch_assoc($q))
{
$newUser = $lastUserID != $row['id'];
if($newUser) {
?>
<a class="main" href="profile.php?id=<? echo $row['id']; ?>"><? echo $row['username']; ?></a>
<ul>
<? }
?>
<li><? echo $row['role']; ?></li>
<? if($newUser) {
?>
</ul>
<? $lastUserID = $row['id'];
}
}
?>

Categories