Jump to content

HELP! I need some help with my PHP! I'm in dire straights :(


Recommended Posts

Hi,

 

I have a few issues i need to address with app that I'm hoping someone can help me with! Pretty please :D

 

Firstly. My sessions! Basically i need to assign some pages to be viewed by only users and some by only admin. At the moment, you type in the address of any of the pages and you can see them. I need to get my sessions working too.

 

Secondly i'm trying to extract data from a MySQL table into a html/php table to be viewed.

        <?php
	include ('/content/base.php');
	$query1 = mysql_query("SELECT * FROM testablishment");
	echo "<table border ='1'>
		<tr>
		<th>Establishment ID</th>
		<th>Establishment Name</th>
		<th>Establishment URL</th>
		<th>User ID</th>
		</tr>";
	while($row = mysql_fetch_array($query1)){
		echo "<tr>";
		echo "<td>" . $row['cEstablishmentID'] . "</td>";
		echo "<td>" . $row['cEstablishmentName'] . "</td>";
		echo "<td>" . $row['cEstablishmenURL'] . "</td>";
		echo "</tr>";
	}
	echo "</table>";
	?>
       	

 

That's my code and i'm getting this error : Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given. Anyone can help me with that?

 

Thanks in advance!

 

Sorry!

 

Okay so this is my index page:

<?php include "content/base.php"; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<title>Login</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>  
<body>  

<div id="main">
<h1>B'n'B Hospitality Service Providers Portal</h1><br />
<h2>Member Login</h2> 
<p>Thanks for visiting! Please either login below, or <a href="register.php">click here to register</a>.</p>
    
<form method="post" action="validate/validate.php" name="loginform" id="loginform">
<fieldset>
	<label for="username">Username:</label><input type="text" name="username" id="username" /><br />
	<label for="password">Password:</label><input type="password" name="password" id="password" /><br />
	<input type="submit" name="login" id="login" value="Login" />
</fieldset>
</form>

</div>

<?php
	if(!isset($_SESSION))
	{
		session_start();
		session_id();
		$_SESSION['username']= "";
		$_SESSION['LoggedIn'] = false;
		$_SESSION['userID']= "";
		$_SESSION['userType'] = "";
	} 


?>

</body>
</html>

 

And this is the verify login page:

<head>	
<title>Registration</title>
<link rel="stylesheet" href="../style.css" type="text/css" />
</head>
<body>
<div id="main">

<?php
include ('../content/base.php');
$username = $_POST['username'];
$password = $_POST['password'];
$login = mysql_query("SELECT * FROM tuser WHERE (cUserName = '" . mysql_real_escape_string($username) . "') 
AND (cUserPassword = '" . mysql_real_escape_string(md5($password)) . "')");

echo mysql_error();

if(mysql_num_rows($login) == 1)
{
	$_SESSION['LoggedIn'] = true;
	$_SESSION['username'] = $username;
	$_SESSION['userID'] = mysql_query("SELECT cUserID FROM tuser WHERE cUserName = '". $username ."'");
	$_SESSION['userType'] = mysql_query("SELECT cUserType from tuser WHERE cUserName = '". $username . "'");

	$userstatus = mysql_query("SELECT cUserType FROM tuser WHERE cUserName = '" . $username . "'");
	$result = mysql_fetch_assoc($userstatus);

	if($result['cUserType'] == "user") 
	{
		echo "Welcome to our user portal ".$_SESSION['username'];
		echo '<META HTTP-EQUIV="Refresh" Content="2; URL=../usercp.php">';
	}
		else 
		{
			echo 
			header('Location: ../adminCP.php');
		}
}
else 
{
	echo "Login failed<br />";
	echo "Go <a href='index.php'>try again now</a> or wait for automatic refresh"; 
	echo '<META HTTP-EQUIV="Refresh" Content="2; URL=../index.php">';
}

?>
</div>	
</body>

And the code im using to 'compartmentalize' the pages between admin and user:

<?php include "content/base.php"; 
if($_SESSION['LoggedIn'] = true)
{

}else{
	echo "click <a href = ../index.php> here </a> to login";
}
if($_SESSION['userType'] = "admin")
{
	echo "You're logged in as an admin";
}else
{

}

?>
<!DOC

 

And my logout page:

<?php include "content/base.php";
$_SESSION = array();
session_destroy(); 
$_SESSION['username']= "";
$_SESSION['LoggedIn'] = false;
$_SESSION['userID']= "";
$_SESSION['userType'] = "";

?>
<meta http-equiv="refresh" content="0;index.php">

 

Basically, it's not doing anything it's meant to.

 

It's showing "youre logged in as an admin" on every page". If you log out, you can still access pages. The logout isn't destroying sessions.

 

 

Thanks in advance

Anytime you're working with sessions you must first start the session by placing this at the top of your script (or at least before any use of $_SESSION comes into play):

 

session_start();

 

It appears you are including base.php with each file, so it might be wise to place session_start(); in there.

 

You also don't seem to have a firm grasp of how queries work.  In your 'verify login' page, for example:

 

$_SESSION['userID'] = mysql_query("SELECT cUserID FROM tuser WHERE cUserName = '". $username ."'");

 

mysql_query() returns a resource on success and FALSE on failure.  You go on to pull from the `tuser` table ~4 times within that script.

 

OK - so place session_start(); in your base.php file, and remove it from this block:

 

if(!isset($_SESSION))
	{
		session_start(); // REMOVE
		session_id();
		$_SESSION['username']= "";
		$_SESSION['LoggedIn'] = false;
		$_SESSION['userID']= "";
		$_SESSION['userType'] = "";
	}

 

Try this for your 'verify login' page:

 

<head>	
<title>Registration</title>
<link rel="stylesheet" href="../style.css" type="text/css" />
</head>
<body>
<div id="main">

<?php
include ('../content/base.php'); // make sure to include session_start(); in base.php
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM tuser WHERE (cUserName = '" . mysql_real_escape_string($username) . "') AND (cUserPassword = '" . md5($password) . "') LIMIT 1";
if ($result = mysql_query($sql)) {
	if (mysql_num_rows($result) == 1) {
		if ($row = mysql_fetch_assoc($result)) {
			$_SESSION['LoggedIn'] 	= true;
			$_SESSION['username'] 	= $username;
			$_SESSION['userID'] 	= $row['cUserID'];
			$_SESSION['userType'] 	= $row['cUserType'];

			if ($row['cUserType'] == "user") {
				echo "Welcome to our user portal ".$_SESSION['username'];
				echo '<META HTTP-EQUIV="Refresh" Content="2; URL=../usercp.php">';
			}
			else {
				header('Location: ../adminCP.php');
			}
		}
	}
	else {
		echo "Login failed<br />";
		echo "Go <a href='index.php'>try again now</a> or wait for automatic refresh"; 
		echo '<META HTTP-EQUIV="Refresh" Content="2; URL=../index.php">';
	}
}
else {
	trigger_error(mysql_error());
}
?>
</div>	
</body>

 

I removed mysql_real_escape_string() from $password in the query as you're already hashing the password using md5().  Both are not necessary.

 

Avoid mixing <meta refresh> within PHP.  Just use header('Location: /some_file.php');

And the conditions within the following block of code will return TRUE every time as you are not using a comparison operator:

 

<?php include "content/base.php"; 
if($_SESSION['LoggedIn'] = true)
{

}else{
echo "click <a href = ../index.php> here </a> to login";
}
if($_SESSION['userType'] = "admin")
{
echo "You're logged in as an admin";
}else
{

}

?>

 

if($_SESSION['LoggedIn'] = true)

 

Will always validate.  You need to use the following when checking specific variable types:

 

if($_SESSION['LoggedIn'] === true)

 

That will check that $_SESSION['LoggedIn'] is of the same value AND type.  Otherwise, simply using a double operator like so:

 

if($_SESSION['LoggedIn'] == true)

 

Will only test the value and not the type, so:

 

if($_SESSION['LoggedIn'] == true)

 

Woudl return validate if $_SESSION['LoggedIn'] was TRUE or 'true' (Boolean or string).

 

However, simply using the following:

 

if($_SESSION['LoggedIn'])

 

Will help you get things going.  Same is applicable for the second condition in that block:

 

if($_SESSION['userType'] = "admin")

Thank you so much!

 

Yeah, i'm unfortunately terribly noob :/

 

Just to clarify:

 

In the base.php i should start my session so the variables are open, correct?

So something like this:

<?php
session_start();
if(!isset($_SESSION))
	{
		session_id();
		$_SESSION['username']= "";
		$_SESSION['LoggedIn'] = false;
		$_SESSION['userID']= "";
		$_SESSION['userType'] = "";
	}

$dbhost = "localhost"; // this will ususally be 'localhost', but can sometimes differ
$dbname = "aa2"; // the name of the database that you are going to use for this project
$dbuser = "root"; // the username that you created, or were given, to access your database
$dbpass = ""; // the password that you created, or were given, to access your database

mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
?>

 

and checking the variable i should always use === or is it situational?

 

Just to make sure i'm kinda grasping it:

	if($_SESSION['LoggedIn'] === true)
{

}else{
	echo "click <a href = ../index.php> here </a> to login";
}
if($_SESSION['userType'] == "admin")
{
	echo "You're logged in as an admin";
}else
{

}

 

As the 'userType' is a word i'm using == and the LoggedIn is a boolean so i'm using ===

 

Correct?

 

Thanks again!

If that's your base.php file, then yes, I would suggest placing it in there as it seems all your scripts are accessing $_SESSION.  Instead of having to include it in each file since you're already including base.php anyways.

 

PHP Comparison Operators

 

Comparison operators are situational.  == vs === are quite different.  == is not as strict as === as:

 

$foo = true;

if ($foo == 'true') // success

// and

if ($foo == true) // success

 

are both valid and will return TRUE/success.

 

However, this is where things can get tricky if you don't have a firm grasp of what each comparison operator does:

 

<?php
// http://www.example.com/?id=12345

$id = $_GET['id'];

if ($id === 12345) // fail; $id is a string and 12345 is an integer; they are of same value, but NOT type

if ($id == 12345) // success

if ($id == '12345') // success

if ($id === '12345') // success

 

^ not applicable to your application, but just a quick tutorial on these 2 operators.  There are times when this comes in handy as you can probably see why.  Whenever you can check a variable type, go for it.  However, this can lead to a lot of noobie problems if you don't fully understand their differences.

 

Flip side:

 

<?php
$id = 12345;

if ($id === 12345) // success; same value and type

if ($id == 12345) // success

if ($id == '12345') // success

if ($id === '12345') // fail

 

$id is a set integer, so the last comparison will fail as it's a check against $id having a value of 12345 and a string.

Just to make sure i'm kinda grasping it:

	if($_SESSION['LoggedIn'] === true)
{

}else{
	echo "click <a href = ../index.php> here </a> to login";
}
if($_SESSION['userType'] == "admin")
{
	echo "You're logged in as an admin";
}else
{

}

 

As the 'userType' is a word i'm using == and the LoggedIn is a boolean so i'm using ===

 

Correct?

 

This will work, yes.

 

I like to use strict comparisons on $_SESSION values as sessions can be hijacked in a similar fashion to cookies.  That meaning, if you set your $_SESSION['LoggedIn'] variable to (bool)TRUE during a successful login, then you might as well check it to ensure it still contains that bool type.

 

If you lazy out and do something like the following:

 

if ($_SESSION['LoggedIn']) { // this has no comparison checks other than whether $_SESSION['LoggedIn'] has a value; is widely used by developers (unfortunately)

 

Then that $_SESSION['LoggedIn'] variable could be anything and still return true, executing your code and allowing the user to get in.

 

Summary: == has a purpose, as does ===.  Just know when to use them, and when not to.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.