0

I'm hoping someone can help me with my problem. Basically what I am trying to create is a log in system, whereas customers can log in to view their package details (address, billing number etc.) But i'm confused on how I can display a customers results based upon who has logged in.

So far I have 2 tables, one called userlogin and one called userinfo. Userlogin simply contains username and password data, whereas userinfo will contain all of the the customers information (address, billing number etc.). These two tables share a row with the same value, user_id. I have tryed to use MYSQL inner join and such, but i'm unsure where I am going wrong, and why I can't return one users information, and it instead shows me all results, or none.

Here is the code for my 2 pages, first the log in page.

    //Login.php
session_start();
if($user_is_valid) {
    //Store the id in the session
    $_SESSION['user_id'] = $user_id;

    //Redirect to the home-page
    header('Location: home.php');
    exit;
}
////// Login Section.
$Login=$_POST['Login'];
if($Login){ // If clicked on Login button.
    $username=$_POST['username'];
    $password=$_POST['password']; // Encrypt password with md5() function.

    // Connect database. 
    //connect
    $con = mysql_connect("*****","*****","*****");
    if (!$con){
        die('Could not connect: ' . mysql_error());
    }
    //datebase
    mysql_select_db("*****", $con);

    // Check matching of username and password.
    $result=mysql_query("select * from userlogin where username='$username' and password='$password'");
    if(mysql_num_rows($result)!='0'){ // If match.
    $_SESSION ['user']['id'] = $result ['id'];
        session_register("username"); // Craete session username.
        header("location:home.php"); // Re-direct to main.php
        exit;
    }
    else { // If not match.
        $message="--- Invalid Username or Password ---";
    }

} // End Login authorize check.

and here is the home page (the page which will display the customers information).

//Home.php
if(!strlen(trim($_SESSION['username']))) {
 header("Location:login.php");
 exit();
}
session_start();
echo $_SESSION['user_id']; //This will output the value we set earlier

$con = mysql_connect("*****","*****","*****");
if (!$con){
    die('Could not connect: ' . mysql_error());
}
//datebase
mysql_select_db("*****", $con);
//select
$user_id = $_GET['user_id'];
$result = mysql_query("SELECT userinfo.name as name, userinfo.address as address, userlogin.username as username  
                       FROM userinfo
                       INNER JOIN userlogin ON userlogin.user_id = userinfo.user_id
                       WHERE userlogin.user_id = userinfo.user_id");

while($row = mysql_fetch_array($result)){
    echo $row['name'] . '</br> ';
    echo $row['username'] . '</br> ';
    echo $row['address'] . '</br> ';
}

So in a nut shell, what I am trying to do is create a system whereas a user can go onto our website, log in and then have their information displayed for them, but i'm unsure where I have go wrong, and quite honestly I've confused myself.

I understand that I might not have explained this well, or my code might not be very clean, but please any feedback, questions, or if you could just point me in the right direction i'd greatly appreciate it! Thank you!

King
  • 1
  • 2
  • I think the first thing that will really help you is to tidy up your code. This sounds pedantic but is crucial in determining if the flow of the code is what you think it is. In particular the 3rd/4th line of the second example is a big risk of ambiguity as you break out of PHP and then back in, with little certainty whether your conditional statement is still being evaluated. I'm aware that maybe some is just how it's formatted on this site, but it helps everyone to have consistent coding standards. I'll do what I can with an edit. – M1ke Jan 13 '14 at 11:27
  • 2
    Sanitize the request before using the values unescaped in your SQL-query or use a prepared query. Your user_id variable on your second page home.php is retrieved from the query-string, but it appears it is never actually passed along to home.php. What about storing the id of the currently logged in user in the session? You should also consider that anyone (in your current setup) can view the details of any user simply by changing the user_id in the request. You need to assert the identity of the currently logged in user and determine what resources they have access to. – oens Jan 13 '14 at 11:28
  • Agree with Morteza; you've got some correct code in here but the way to start developing web apps isn't to blindly hack things - PHP is a good language but it's very easy to pick up bad habits early on. There's other feedback I'd give on your query (you don't need the aliases or the join) but starting properly is the best advice. – M1ke Jan 13 '14 at 11:37
  • Oh, and before doing any more MySQL ditch mysql_ and use mysqli_ functions with [prepared statements](http://mattbango.com/notebook/code/prepared-statements-in-php-and-mysqli/) – M1ke Jan 13 '14 at 11:38
  • @MortezaEdalati and M1ke Thanks for the feedback, i'm currently looking and learning about mysqli_ at the moment, but I didn't feel comfortable using it just yet. Would you suggest that this would be the best way forward? – King Jan 13 '14 at 11:48
  • @oens Thanks for the feedback, sadly I have little to no knowledge on using sessions and wouldn't know how to store the id within this session, could you elaborate further? – King Jan 13 '14 at 11:50
  • @King You shouldn't use mysql_ functions at all. Start with mysqli_; it won't solve this particular problem but is "the right way" to do things - no point learning bad habits that you then have to lose. – M1ke Jan 15 '14 at 15:45

2 Answers2

0

change:

$result = mysql_query("SELECT userinfo.name,userinfo.address,userinfo.username  
FROM userinfo
INNER JOIN userlogin ON userlogin.user_id = userinfo.user_id
WHERE userlogin.user_id = $user_id;");

into

$result = mysql_query("SELECT userinfo.name,userinfo.address,userinfo.username  
FROM userinfo
INNER JOIN userlogin ON userlogin.user_id = userinfo.user_id
WHERE userlogin.user_id = $user_id");

you have a semicolon after your php var .

Gert B.
  • 2,282
  • 18
  • 21
0

You can consider the session as a place to store state between "pageloads"/requests. In this case state could be whether the user has been authenticated and if so what identity the current user has. For example, when the user is logged in and you have verified their identity in the database/backend you initialize a session and store their user id. This allows you to retrieve this id in any following requests until you destroy the session.

//Login.php
session_start();
if($user_is_valid) {
    //Store the id in the session
    $_SESSION['userid'] = $userId;

    //Redirect to the home-page
    header('Location: Home.php');
    exit;
}

This allow us to retrieve userid on any subsequent pageloads by simply initializing the session and getting the contents of $_SESSION['userid'], like so:

//Home.php
session_start();
echo $_SESSION['userid']; //This will output the value we set earlier

Finally, maybe we also need a page that clears what we have stored in the session for the current user, i.e. in the case the user wants to log out:

//Logout.php
session_start();
$_SESSION = array();
session_destroy();

This setup also makes sure that the user can only see the information they are allowed to. Even though sessions can be tampered with if one is not careful they are a lot harder to mess with than simply changing some parameter in the query-string.

As for your actual database interaction I would recommend switching to mysqli or MySql PDO as the old mysql has been deprecated, see: http://php.net/pdo_mysql or http://php.net/mysqli

This also allow you to easily take advantage of prepared statements as an easy way for avoiding SQL-injection problems. Obviously, there is some overhead and issues connected to using prepared statements as well, but in your case I think it would be easiest for you. Check out MySQL Prepared Statements or do a quick stackoverflow search.

Community
  • 1
  • 1
oens
  • 370
  • 3
  • 13
  • 1
    Thanks for the feedback, I've edited my code accordingly (check original post) However the problem still persists, as on my home page all of my results from the database are still being displayed and I still can't understand why. Also thank you for the links regarding PDO and mysqli, you'll be glad to know I'm currently in the process of trying to implement these. – King Jan 15 '14 at 10:26
  • @King My suggestions above was not meant as a plug-and-play solution (you have just pasted them in your code). The variables are placeholders, so you need to add the logic that actually makes it work. In regards to your SQL I believe you are missing a restriction in your WHERE clause, something like this: `SELECT userinfo.* FROM userinfo JOIN userlogin ON userlogin.user_id = userinfo.user_id WHERE userlogin.user_id = $user_id` where $user_id is your variable containing the id for the user you want to look up. – oens Jan 17 '14 at 18:05