Linking the User Login Sytem to the Profile System

Post here is you are having problems with any of the tutorials.
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Linking the User Login Sytem to the Profile System

Post by jaymeh »

Hello Everyone,

I am currently trying to link the user profile system to the login system which were created in the PHP tutorials on youtube. The only problem which I am currently having is linking both the username and the uid together so that each can be used.

For example I am trying to use a select statement within the login section which uses a mysql query to link the username session variable to the uid session variable. The statement looks like it may work to me, but perhaps it is placed in the wrong section of my code or the mysql syntax is incorrect.
if(empty($errors))
	{
			add_user($_POST['username'], $_POST['password']);
			
			$_SESSION['username'] = htmlentities($_POST['username']);
			
			$_SESSION ['uid']= mysql_query("SELECT (`user_id`) FROM `users` WHERE `user_username` = '{$_SESSION['username']}'");
			
			header('Location: profile.php');
			die();
	}
The following section would be placed on both my login.php page and my register.php page.

Thanks in advance for any help
Jaymeh
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Linking the User Login Sytem to the Profile System

Post by Temor »

mysql_query will not output the result of your query. You will have to extract it ( using mysql_result ) before you put it in the $_SESSION['uid'] variable.
Also, there should not be a space between $_SESSION and ['uid'] .
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Linking the User Login Sytem to the Profile System

Post by jaymeh »

Thank you very much for your help with that. I have changed the statement to:
$_SESSION['uid']= mysql_result("SELECT (`user_id`) FROM `users` WHERE `user_username` = '{$_SESSION['username']}'")

echo $_SESSION['uid'];


Unfortunately the code still does not redirect me to the profile page. To check if the uid has been set correctly i put an echo statement before the redirect but this still does not work.
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Linking the User Login Sytem to the Profile System

Post by Temor »

jaymeh wrote:Thank you very much for your help with that. I have changed the statement to:
$_SESSION['uid']= mysql_result("SELECT (`user_id`) FROM `users` WHERE `user_username` = '{$_SESSION['username']}'")

echo $_SESSION['uid'];


Unfortunately the code still does not redirect me to the profile page. To check if the uid has been set correctly i put an echo statement before the redirect but this still does not work.
Still doing it wrong :)

You have to run the query, save the result of that query and then get the uid from that result.
$result = mysql_query("SELECT (`user_id`) FROM `users` WHERE `user_username` = '{$_SESSION['username']}'")
$_SESSION['uid'] = mysql_result($result);

echo $_SESSION['uid'];
that should work :)
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Linking the User Login Sytem to the Profile System

Post by jaymeh »

That worked great, thanks very much for your help yet again. It redirected to the profile page.

Of course now, I run into yet another big problem.

So I have the profile page now, but I believe that the session variable of uid is actually empty. Whenever I try to echo it onto the profile page the user id comes up blank.
f($userinfo == false)
		{
		
			echo 'Sorry, the user does not exist.';
			echo "the following variable is ".$_SESSION['uid'];
			
		}
displays
Sorry, the user does not exist.the following variable is

Do you have any ideas why this is?

Thanks again and once again thank you for your help so far :D

Jaymeh
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Linking the User Login Sytem to the Profile System

Post by Temor »

Can you post all the code you have so far?

Is the $_SESSION['username'] variable set?

What does your database look like?
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Linking the User Login Sytem to the Profile System

Post by jaymeh »

Sure, do you want a printscreen of my phpadmin tables, or is there a simpler way?
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Linking the User Login Sytem to the Profile System

Post by Temor »

jaymeh wrote:Sure, do you want a printscreen of my phpadmin tables, or is there a simpler way?
screenshot works just fine :)
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Linking the User Login Sytem to the Profile System

Post by jaymeh »

register.php
<?php

include ('core/init.inc.php');

$errors = array();

if (isset($_POST['username'], $_POST['password'], $_POST['repeat_password']))
{
	if (empty($_POST['username']))
	{
		$errors[] = 'The username cannot be empty.';	
	}
	if (empty($_POST['password']) || empty($_POST['repeat_password']))
	{
		$errors[] = 'The password cannot be empty.';
	}
	if ($_POST['password'] !== $_POST['repeat_password'])
	{
	$errors	[] = 'Password verification failed.';
	}
	
	if(user_exists($_POST['username']))
	{
		$errors[] = 'The username you entered is already taken.';	
	}
	
	if(empty($errors))
	{
			add_user($_POST['username'], $_POST['password']);
			
			$_SESSION['username'] = htmlentities($_POST['username']);
			
			$result = mysql_query("SELECT (`user_id`) FROM `users` WHERE `user_username` = '{$_SESSION['username']}'");
			$_SESSION['uid'] = mysql_result($result);#
			
			$uid=$_SESSION['uid'];
			 
			header("Location: profile.php?uid=" . $_SESSION['uid']);
			die();
	}
	
}


?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Register New User</title>
</head>
<body>
	<p>
    	<?php
		
		if(empty($errors) === false)
		{
			?>
        	<ul>
        		<?php
			
					foreach($errors as $error)
					{
						echo "<li>{$error}</li>";	
					}
		
				?>
       		</ul>
        	<?php
		}
		
		?>
    </p>
    <p>
    <form action="" method="post"/>
    	<p>
        	<label for="username">Username: </label>
            <input type ="text" name="username" id="username" value="<?php if (isset($_POST['username'])) echo htmlentities($_POST['username']); ?>"/>
        </p>
        <p>
        	<label for="password">Password: </label>
            <input type ="password" name="password" id="password"/>
        </p>
        <p>
        	<label for="repeat_password">Repeat Password: </label>
            <input type ="password" name="repeat_password" id="repeat_password"/>
        </p>
        <input type="submit" value="Register" />
        
</body>
</html>
login.php
<?php

include('core/init.inc.php');

$errors = array();

if (isset($_POST['username'], $_POST['password']))
{
	if (empty($_POST['username']))
	{
		$errors[] = 'The username cannot be empty.';	
	}
	if (empty($_POST['password']))
	{
		$errors = 'The password cannot be empty.';
	}
	
	if (valid_credentials($_POST['username'], $_POST['password']) === false)
	{
		$errors = 'Username/Password incorrect.';
	}
	
	if (empty($errors))
	{
		$_SESSION['username'] = htmlentities($_POST['username']);
			
			$result = mysql_query("SELECT (`user_id`) FROM `users` WHERE `user_username` = '{$_SESSION['username']}'");
			$_SESSION['uid'] = mysql_result($result);
			
			$uid=$_SESSION['uid'];
			 
			header("Location: profile.php?uid=['$uid']");
			die();
	}
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<div>
	<?php
	
	if (empty($errors) == false)
	{
	?>
    	<ul>
        	<?php
			
			foreach ($errors as $error)
			{
				echo "<li>($error)</li>";
			}
			
			?>
        </ul>
    <?php
	}
	else
	{
		echo 'Need an account? <a href="register.php">Register here</a>';
	}
	
	?>
</div>
<form name="login" action="" method="post">
<p>
	<label for="username">Username: </label>
    <input type="text" name="username" id="username" value="<?php if (isset($_POST['username'])) echo htmlentities($_POST['username']); ?>" />
</p>
<p>
	<label for="password">Password: </label>
    <input type="password" name="password" id="password" />
</p>
<p>
	<input type="submit" value="Login" />
</p>
</form>
</body>
</html>
profile.php
<?php

include('core/init.inc.php');

$userinfo = fetch_user_info($_GET['uid']);

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php echo $userinfo ['username']; ?>'s Profile</title>
</head>
<body>
	<div>
    
    <?php
		
		if($userinfo == false)
		{
		
			echo 'Sorry, the user does not exist.';
			echo "the following variable is ".$_SESSION['uid'];
			
		}
		else
		{	
		?>
        	<h1><?php echo $userinfo ['firstname']; ?> <?php echo $userinfo ['lastname']; ?></h1>
    		<p>Username: <?php echo $userinfo ['username']; ?></p>
   			<p>First Name: <?php echo $userinfo ['firstname']; ?></p>
    		<p>Last Name: <?php echo $userinfo ['lastname']; ?></p>
            <p>Gender: <?php echo ($userinfo ['gender'] == 1) ? 'Male' : 'Female'; ?></p>
    		<p>Email: <?php echo $userinfo ['email']; ?></p>
   			<p>Location: <?php echo $userinfo ['location']; ?></p>
    		<p>About: <?php echo $userinfo ['about']; ?></p>
            
    	</div>
    <?php
		}
	?>
</body>
</html>
userinc.php
<?php

//'SELECT user_id AS "id", user_username AS "username" FROM users'



//fetches all of the users from the table

function fetch_users()
{
	$query = 'SELECT user_id, user_username FROM users';

	$result = mysql_query('SELECT user_id AS `id`, user_username AS `username` FROM users');
	
	$users = array();
	
	while(($row = mysql_fetch_assoc($result)) !==false)
	{
		
		$users[] = $row;

	}
	
	return $users;
	
}
//fetches profile information for the given user
function fetch_user_info($uid)
{
	
	$uid=(int)$uid;
	
	$sql = "SELECT 
				 `user_username` AS `username`,
				 `user_firstname` AS `firstname`,
				 `user_lastname` AS `lastname`,
				 `user_email` AS `email`,
				 `user_location` AS `location`,
				 `user_about` AS `about`,
				 `user_gender` AS `gender`
				 FROM `users`
				 WHERE `user_id` = {$uid}";
				 
	$result = mysql_query($sql);
	
	return mysql_fetch_assoc($result);
	
}

//updates the current users profile info
function set_profile_info($email, $location,$about)
{
	$email 		= mysql_escape_string(htmlentities($email));
	$about 		= mysql_escape_string(nl2br(htmlentities($about)));
	$location 	= mysql_escape_string($location);
	
	$sql = "UPDATE `users` SET
				`user_email` = '{$email}',
				`user_about` = '{$about}',
				`user_location` = '{$location}'
				
			WHERE `user_id` = {$_SESSION['uid']}";
	
	mysql_query($sql);
	
}

//checks if the given username exists in the database
function user_exists($user)
{
	$user = mysql_real_escape_string($user);
	
	$total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_username` = '{$user}'");
	
	return (mysql_result($total, 0) == '1') ? true : false;
}

//checks if the given username and password combination is valid
function valid_credentials($user, $pass)
{
	$user = mysql_real_escape_string($user);
	$pass = sha1($pass);
	
	$total = mysql_query("SELECT COUNT(`user_id`) FROM `users` WHERE `user_username` = '{$user}' AND `user_password = '{$pass}'");
	
	return (mysql_result($total, 0) == '1') ? true : false;
	
}

//adds a user to the datatabase
function add_user($user, $pass)
{
	$user = mysql_real_escape_string(htmlentities($user));
	$pass = sha1($pass);
	
	mysql_query("INSERT INTO `users` (`user_username`, `user_password`) VALUES ('{$user}', '{$pass}')");
}

?>
Attachments
table data
table data
tabledata.jpg (276.42 KiB) Viewed 6530 times
table structure
table structure
tablestruc.jpg (317.02 KiB) Viewed 6530 times
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Linking the User Login Sytem to the Profile System

Post by Temor »

Try making it a function, like this:
function fetch_user_id($username){
	$username = mysql_real_escape_string($username);

	$result = mysql_query("SELECT `user_id` FROM `users` WHERE `user_username` =  '{$username}' ");
	

	return mysql_result($result,0);
}
and then call it where you need it like this:
<?php
$user_id = fetch_user_id($_SESSION['username']);
?>
I totally forgot you need to put in a second parameter into mysql_result.
What you have to do is put a 0 after $result like this:
$thing = mysql_result($result,0);
If you want the first result and 1 if you want the second result and so on.

I hope that works. Let me know if it still doesn't work and I'll take a closer look.
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Linking the User Login Sytem to the Profile System

Post by jaymeh »

That worked like a treat.

Thank you very much my good man, if I am ever in your area I owe you a beer :D.

Thanks again
Jaymeh
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Linking the User Login Sytem to the Profile System

Post by jaymeh »

Well the Register page works well anyway. All I did was copy and paste some of the code from the registration page but I am still having problems with the login process. For some reason it won't redirect to the profile page. It just sticks on the login page and resets all of the form data. Here is the code I have used.
<?php

include('core/init.inc.php');

$errors = array();

if (isset($_POST['username'], $_POST['password']))
{
	if (empty($_POST['username']))
	{
		$errors[] = 'The username cannot be empty.';	
	}
	if (empty($_POST['password']))
	{
		$errors = 'The password cannot be empty.';
	}
	
	if (valid_credentials($_POST['username'], $_POST['password']) === false)
	{
		$errors = 'Username/Password incorrect.';
	}
	
	if (empty($errors))
	{
		$_SESSION['username'] = htmlentities($_POST['username']);
			
		$_SESSION['uid'] = fetch_user_id($_SESSION['username']);
		
		
		header("Location: profile.php?uid=" . $_SESSION['uid']);
		die();
		echo $_SESSION['uid'];
	}
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<div>
	<?php
	
	if (empty($errors) == false)
	{
	?>
    	<ul>
        	<?php
			
			foreach ($errors as $error)
			{
				echo "<li>($error)</li>";
			}
			
			?>
        </ul>
    <?php
	}
	else
	{
		echo 'Need an account? <a href="register.php">Register here</a>';
	}
	
	?>
</div>
<form name="login" action="" method="post">
<p>
	<label for="username">Username: </label>
    <input type="text" name="username" id="username" value="<?php if (isset($_POST['username'])) echo htmlentities($_POST['username']); ?>" />
</p>
<p>
	<label for="password">Password: </label>
    <input type="password" name="password" id="password" />
</p>
<p>
	<input type="submit" value="Login" />
</p>
</form>
</body>
</html>
Sorry and thanks in advance for your help once more :).
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Linking the User Login Sytem to the Profile System

Post by Temor »

if (empty($errors))
        {
                $_SESSION['username'] = htmlentities($_POST['username']);
                       
                $_SESSION['uid'] = fetch_user_id($_SESSION['username']);
               
               
                header("Location: profile.php?uid=" . $_SESSION['uid']);
                die();
                echo $_SESSION['uid'];
        }
there's no idea echoing something out right after a die(); seeing as it will kill the script to prevent it from running more code :)

With that said, I have no idea why it isn't redirecting... Do you get any errors or is anything else acting strange?
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Linking the User Login Sytem to the Profile System

Post by jaymeh »

Ok then, well I don't get any errors outputted but I don't think the valid credentials works because I tried it with an incorrect password combination and it didn't output the error message. I'm not sure if this has something to do with it.

valid_credentials is a php function isn't it? If its not it may be incorrect in my include file.
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Linking the User Login Sytem to the Profile System

Post by Temor »

I really don't know why it's not working.
I can't spot any typos or anything else that might cause the script to fail without giving any errors.

Do you have error reporting on?

Set error_reporting = E_ALL in your php.ini if it's not already set.

Lets hope someone else has better eyesight than me and can spot what's causing this :)
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Linking the User Login Sytem to the Profile System

Post by jaymeh »

Where would I be able to find the PHP.ini file so I can change the debugging settings? My site is currently hosted on my university server, so I don't have access to a lot of features.
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Linking the User Login Sytem to the Profile System

Post by Temor »

jaymeh wrote:Where would I be able to find the PHP.ini file so I can change the debugging settings? My site is currently hosted on my university server, so I don't have access to a lot of features.
I don't know how you can get access to the php.ini file on that specific server.
You can, on the other hand set the value in your script. All you have to do is run this function on top of your code.
<?php

error_reporting(E_ALL);
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Linking the User Login Sytem to the Profile System

Post by jaymeh »

Thanks thats better at least I know a little more about whats wrong. I have included that in the login page. valid_credentials was a function used in my user.inc.php file. Here are the errors I received from the page when I ran it.

Warning: mysql_result(): supplied argument is not a valid MySQL result resource in /web/stud/u0963643/userprofilesection/finaluserprofile/core/inc/user.inc.php on line 95

Warning: Invalid argument supplied for foreach() in /web/stud/u0963643/userprofilesection/finaluserprofile/login.php on line 55

line 95 of valid credentials function on user.inc.php
return (mysql_result($total, 0) == '1') ? true : false;

for each function on line 55 is
foreach ($errors as $error)
			{
				echo "<li>($error)</li>";
			}
Ill check through the tutorials to make sure the syntax is the same aswell.

Thanks
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Linking the User Login Sytem to the Profile System

Post by Temor »

I spotted something.
$result = mysql_query("SELECT (`user_id`) FROM `users` WHERE `user_username` = '{$_SESSION['username']}'");
there should not be a space between SELECT and (`user_id`).

Login.php line 27

/Edit; You could remove the parentheses altogether even.
jaymeh
Posts: 27
Joined: Wed Jan 04, 2012 12:42 pm
Location: West Yorkshire

Re: Linking the User Login Sytem to the Profile System

Post by jaymeh »

Sorry, which function would this code need to be corrected?
$result = mysql_query("SELECT (`user_id`) FROM `users` WHERE `user_username` = '{$_SESSION['username']}'");
Or do you mean that this line needs placing on line 27 of login.php?

Thanks again
Jamie
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Linking the User Login Sytem to the Profile System

Post by Temor »

jaymeh wrote:Sorry, which function would this code need to be corrected?
$result = mysql_query("SELECT (`user_id`) FROM `users` WHERE `user_username` = '{$_SESSION['username']}'");
Or do you mean that this line needs placing on line 27 of login.php?

Thanks again
Jamie
Nevermind my previous post. That was entirely my 39ºc fever talking.

What you could do is add mysql_error(); after your query to see if it is failing.

do that for all your queries and let me know if it tells you anything.
Post Reply