Beginner PHP Tutorial – 142 – Getting User Data Part 2

[ad_1]
Facebook –
GitHub –
Google+ –
LinkedIn –
reddit –
Support –
thenewboston –
Twitter –


Posted

in

by

Tags:

Comments

45 responses to “Beginner PHP Tutorial – 142 – Getting User Data Part 2”

  1. Imroz Wana Avatar

    My codes are bit different but its working fine..

    index.php
    —————-
    <?php
    include ('login.php');
    if (!empty($_SESSION['user_id']))
    {
    header('Location: profile.php');

    }

    ?>

    <!DOCTYPE html>
    <html>
    <head>
    <title></title>
    <link rel="stylesheet" type="text/css" href="login.css">
    </head>
    <body>

    <div id="main">
    <h1> Login Form </h1>
    <div id="login">

    <form action="" method="POST">
    <p> Username </p>
    <input id="name" type="text" name="username" placeholder="username">
    <p> Password </p>
    <input id="password" type="password" name="password" placeholder="*********">
    <input class="but" type="submit" name="submit" value="Login">

    <span id="index_span"><?php echo $error1; ?></span>
    <span id="index_span1"><?php echo $error; ?></span>

    </form>

    </div>

    </div>

    </body>
    </html>

    ———————————————————————————————————————————————-
    login.php
    ————–
    <?php
    session_start();
    $error = "";
    $error1= "";

    $connection = mysqli_connect("localhost", "root", "" , "adatabase");

    if (isset($_POST['submit']))
    {

    if (empty($_POST['username']) || empty($_POST['password']) )
    {
    $error1= 'Error!'."<br/>".'Please fill all the fields';
    }
    else
    {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $password_hash = md5($password);

    if ($connection)
    {
    $username = stripslashes($username);
    $password = stripslashes($password);
    $username = mysqli_real_escape_string($connection,$username);
    $password = mysqli_real_escape_string($connection,$password);

    $query = "SELECT id FROM user_registration WHERE user_id='$username' AND password ='$password_hash' ";
    $query_run = mysqli_query($connection,$query);
    $query_row = mysqli_num_rows($query_run);

    if ($query_row==0)
    {
    $error ='Error!'."<br/>". "Invalid Username or Password";
    }
    else
    {

    foreach ($query_run as $row)
    {
    $id = $row['id'];
    //$firstname = $row['first_name'];
    //$lastname = $row['last_name'];
    $_SESSION["user_id"] = $id;
    if ($_SESSION["user_id"])
    {

    header('Location: index.php');

    }

    }
    }
    mysqli_close($connection);

    }
    else
    {
    echo "No Database Found!"; // u may not need this.
    }
    }

    }

    ?>
    ————————————————————————————————————————————————
    profile.php
    ——————-
    <?php
    include ('session.php');

    ?>
    <!DOCTYPE html>
    <html>
    <head>
    <title>Profile</title>
    <link rel="stylesheet" type="text/css" href="profile.css">
    </head>
    <body>
    <div id="profile_header">
    <span id="logout_span"><a href="logout.php"> logout</a></span>
    <span>Welcome <?php echo $firstname.$lastname;?></span>

    <h1> Profile page</h1>

    </div>

    </body>
    </html>
    ————————————————————————————————————————————————
    session.php
    ——————–
    <?php
    session_start();
    $current_file = $_SERVER['SCRIPT_NAME'];
    $newid = $_SESSION['user_id'];
    $connection = mysqli_connect("localhost", "root", "" , "adatabase");
    $query = "SELECT * FROM user_registration WHERE id='$newid' ";
    $query_run = mysqli_query($connection,$query);
    $query_row = mysqli_num_rows($query_run);
    if ($query_row==1)
    {
    foreach ($query_run as $row )
    {
    $firstname = $row['first_name'];
    $lastname = $row['last_name'];
    }
    }

    ?>
    ————————————————————————————————————————————————
    logout.php
    —————–
    <?php
    include ('session.php');

    session_destroy();
    header('Location: index.php')

    ?>
    ————————————————————————————————————————————————
    login.css
    —————

    body{
    background-color: lime ;
    }
    #main{
    /*text-align: center; */
    background-color: ivory;
    margin: 80px auto;
    width: 400px;
    height:450px;
    border-radius: 5px;
    box-shadow: 5px 5px 2px grey;

    }
    #login{
    width: 340px;
    height: 367px;

    padding: 10px 30px 25px;
    margin-top: 40px;
    border-top: 0.5px solid black;
    font-family: sans-serif;

    }

    input[type=text],input[type=password] {
    width:250px;
    padding:5px;
    margin-left: 30px;
    border:1px solid #ccc;

    font-size:16px;

    }
    h1{
    margin:20px 0px 0px 100px;

    }

    input[type=submit] {
    width:285px;
    margin-top: 30px;
    padding: 7px;
    margin-left: 20px;
    background-color: skyblue;
    cursor: pointer;
    color: white;
    font-size: 20px;
    font-weight: bolder;
    }
    input[type=submit]:hover { background-color: yellow;}

    p{
    margin-left: 125px;
    }

    ::-webkit-input-placeholder {
    text-align: center;

    }
    #index_span,#index_span1{
    display: block;
    text-align: center;
    background-color: #ff0000;

    margin-top: 30px;
    font-size: 20px;
    font-weight: bold;

    }

    —————————————————————————————————————————————–

    profile.css
    ——————
    *{
    margin: 0 auto;
    padding: 0 auto;
    }
    body{
    background-color: blue;
    }
    #profile_header{
    width: 100%;
    height: 50px;
    background-color: lime;
    }
    h1{
    text-align: center;

    }

    span{
    float: right;
    margin-right: 150px;
    }

    span>a {
    text-decoration: none;
    }
    ———————————————————————————————————————————————

    any improvement or suggestions is welcome.

    thanks.

  2. usama nasar Avatar

    core.inc.php
    ——————–

    ob_start();
    session_start();

    $current_file = $_SERVER['SCRIPT_NAME'];
    if(isset($_SERVER['HTTP_REFERER'])){
    $http_referer = $_SERVER['HTTP_REFERER'];
    }
    function loggedin(){
    if (isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])){
    return true;
    } else {
    return false;
    }
    }
    function getuserfield($field){
    global $connect;

    $query = "SELECT `$field` FROM `users` WHERE `id` = '".$_SESSION['user_id']."'";
    if ($query_run = mysqli_query($connect, $query)){

    while($row = mysqli_fetch_assoc($query_run)){
    $count = $row[$field];
    return $count;
    }

    }
    }

  3. Amirul Zafri Avatar

    Hello, can i ask a question..
    why $field does not have concatenate instead of $_SESSION[user_id]….
    please correct me if I'm wrong, thank you 🙂

    "SELECT '.$field.' FROM 'user' WHERE 'id' = '".$_SESSION['user_id']." ' "

  4. Mervin Lee Avatar

    Hello! I would appreciate if someone could assist me with this. I think the MySQL command is outdated and we should use mysqli but I think I need to connect to my database. I am using the mysqli command and it needs 2 parameters, the first one is my MySQL connect variable and for some reason, it is given me an error. Didn't we already connect this in the other page?

  5. Aleksey _ Avatar

    Just a great idea, 1.000.000+ requests to DB instead of just 1 and putting everything into the session.

  6. Tyler Gerow Avatar

    I can't get anything to return in another column other than the 'email'

  7. adminos15 Avatar

    hello, is it a problem if i use "isLogged = true/false" instead of sessions.
    On first look it is doing the same job.
    You always know when the user is signed in/signed out. "isLogged" will go to 0 when 'logout' is clicked and will be 1 when correct password and username are entered

  8. Kartik Gogia Avatar

    i m able to login and show my name but when i click logout it shows somekind of error…

  9. stephen cabreros Avatar

    nc tutorial ^_^

    index.php
    <?php
    require 'connect.inc.php';
    require 'core.inc.php';
    if(loggedin())
    {
    $firstname = getuserfield('firstname');
    $surname = getuserfield('surname');
    echo 'You're logged in,'.$firstname.' '.$surname.'. <a href="logout.php">Log Out </a><br>';

    }
    else
    {
    include 'loginform.php';
    }

    ?>
    connection.inc.php
    <?php
    $mysql_host='localhost';
    $mysql_user='root';
    $mysql_pass = '';
    $mysql_db = 'a_database';
    mysql_connect($mysql_host,$mysql_user,$mysql_pass);
    if(!mysql_select_db($mysql_db))
    {

    die(mysql_error());
    }
    ?>

    core.inc.php
    <?php
    ob_start();
    session_start();
    $current_file = $_SERVER['SCRIPT_NAME'];
    $http_referer = $_SERVER['HTTP_REFERER'];
    function loggedin()
    {
    if(isset($_SESSION['user_id'])&&!empty($_SESSION['user_id']))
    {
    return true;
    }
    else
    {
    return false;
    }
    }
    function getuserfield($field)
    {
    $query = "SELECT `$field` FROM `users` WHERE `id`='".$_SESSION['user_id']."'";
    if($query_run = mysql_query($query))
    {
    if($query_result = mysql_result($query_run,0,$field))
    {
    return $query_result;
    }
    }

    }
    ?>

    loginform.php
    <?php
    if(isset($_POST['username'])&&isset($_POST['password']))
    {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $password_hash = md5($password);
    if(!empty($username)&&!empty($password))
    {
    $query = "SELECT `id` FROM `users` WHERE `username`='$username'And `password`='$password_hash'";
    if($query_run=mysql_query($query))
    {
    $query_num_rows=mysql_num_rows($query_run);
    if($query_num_rows==0)
    {
    echo 'invalid username and password combination';
    }
    else if($query_num_rows ==1)
    {
    $user_id = mysql_result($query_run,0,'id');
    $_SESSION['user_id'] = $user_id;
    header('Location:index.php');
    }
    }
    }
    else
    {
    echo 'Pls fill in username and password';
    }
    }
    ?>
    <form action="<?php $current_file?>" method="POST">
    Username:<input type ="text" name="username">Password:<input type="password" name="password">
    <input type="submit" value = "Enter">
    </form>
    logout.form
    <?php
    require 'core.inc.php';
    session_destroy();
    header('Location:'.$http_referer);

    ?>

  10. V. Peters Avatar

    ok, so if i understand correctly, the function getuserfield of core.inc.php, is used not once but TWICE within the if statement of index.php….

    ahaaa…

  11. V. Peters Avatar

    even more, tools like phpdesigner 8 and such should make it possible to make such functions clickable and directly linking to the info of the php.net website 😉

    wouldn't you agree?

  12. V. Peters Avatar

    it's not your fault… getuserfield (something that the user made up) should have color BLACK…
    vs something that is actually part of PHP should have color "OTHER-THEN-BLACK "

  13. V. Peters Avatar

    aaaaaaaaaaaaaaaaaaah now I see, mysql_result is part of "php.net"…. http://php.net/manual/en/function.mysql-result.php

    i thought that was a part that you made up….

    and there it says it expects an integer for row….

    mysql_result     blabla, INT $ROW, blabla

    please focus a little bit more on explaining how to connect those dots Alex. that is the part that is going too fast sometimes….

    thanks.

  14. V. Peters Avatar

    I don't get the 0 in the part Alex, 0 stands for row 1, but if there is only to gonna be ever 1 row, why should we specify a 0?

    and how did you know that there should be a 0 stated at that spot?

  15. Russell Kitchen Avatar

    Why would you not just include first name and second name in the first SELECT query?

  16. johan mendez Avatar

    Fatal error: Call to undefined function get_field()

  17. mac VII Avatar

    In this line,
     query = "SELECT 'field' FROM 'users' WHERE 'id'='".$_SESSION['user_id']."' ";

    ' ".$_SESSION['user_id']." ' ——> why double quotes and concatenation operator are used   and why not put it simply  '$_SESSION['user_id']' ?

  18. malnoor83 Avatar

    it works for me $field    thanks ..

  19. Hots heroesofthestorm Avatar

    Resource id #6 Resource id #7 ?

  20. TheAxhol Avatar

    Whats the problemmm

    function getuserfield($field){
    $query = "SELECT 'field' FROM 'users' WHERE 'id'='".$_SESSION['user_id']."'";
    if ($query_result = mysql_query($query)){
    return mysql_result($query_result, 0, $field);
    }
    }

  21. rb1353 Avatar

    My code keeps pulling the opposite user. I log in with one person and it seems to pull the other id. Anyone know why?

  22. JeanAlesiagain3 Avatar

    NOT WORKING????

    try, on index.php:

    if ( loggedIn() )
    {
    echo 'You are logged in, ' . getField('first_name') . ' ' . getField('last_name') . '!';
    }

    try, on core.inc.php:
    function getField($field)
    {
    $query = "SELECT $field FROM users WHERE id = " . $_SESSION['user_id'];

    if ($query_run = mysql_query($query))
    if ( $query_result = mysql_result($query_run, 0, $field) )
    return $query_result;
    }

  23. apreston14 Avatar

    remove double equals from query_run==mysql_query($query)

  24. Forest Solari Avatar

    Is it possible to get the code from this series? or any user can share your file?

  25. isrxi Avatar

    Upss… expired :[ Try this txtup(dot)net/B9UXZ

  26. isrxi Avatar

    Youtube doesn't allow to put all code here so I uploader. Who wanna to fix referer you can disable in htaccess or by including this code: textuploader(dot)com/?p=6&id=99nei

  27. BOSOO ULAAN Avatar

    Notice: Undefined variable: query_result in C:xampphtdocsseriesusersystemcore.inc.php on line 21

    Notice: Undefined variable: query_result in C:xampphtdocsseriesusersystemcore.inc.php on line 21
    You're logged in. Log out (help me)

  28. iedi3 Avatar

    Alex, Bucky …you're the BEST!!

  29. Robert Wilkinson Avatar

    Solid tutorials. 2 thumbs up.

  30. Murad Azmat Avatar

    check your database table firstname and surname fields the spelling must match i was having the same problem in my database table firstname field was typed as firstrname. that was just spelling mistake. gud luck

  31. aiju6 Avatar

    just remove the apostophe from $field..

  32. aiju6 Avatar

    i am getting firstname and surname as the result instead of actual values. what is the reason for that??

  33. zanpaktuh Avatar

    Yet you are the one who was keep posting 'first' Smart ass! Go lecture yourself!

  34. MrLangam Avatar

    Wow.. alex, you are amazing!

  35. Dima lucky Avatar

    alex you are cool thx you!!!

  36. Dan Johnson Avatar

    I don't think it's very efficient to retrieve every field in a separate SQL select using that function.

  37. Jonathan Hilfiker Avatar

    its because where you said select field, you should not put field in single quotes, or that will happen.

  38. Jonathan Hilfiker Avatar

    Yeah, you have to re-do all of his code. Its a bad practice to put assingments in conditions as alex tends to always do and most compilers don't like that. Its harder for others to read your code and you could accidentally assign the wrong thing.

  39. PsTenBox Avatar

    lol, You're tutorials are great but through from "Logging in a user Part 1" there are many things that you're compiler supports that mine didn't although im not going to complain , Since im experienced with php highly I was able to sort around a lot of things and I got here to retrieving data and it worked perfectly.. Thanks for the great work alex.

  40. Chirag Pandit Avatar

    I LOVE YOU ALEXXXXXIE BOY

  41. Red Zambala Avatar

    getting syntax error, unexpected T_VARIABLE

  42. Rob Clardy Avatar

    Take the apostrophe from around $field in the query.

  43. Sunny Sood Avatar

    I am getting only 'firstname' printed out. I cant see why

  44. iinsanebaby Avatar

    @wilky1994 i was having the same problem but i realized i hadnt changed the name of my function in index.php to getuserfield();…. it was still just get user. hope it helps.. somewhat? 😛

Leave a Reply

Your email address will not be published. Required fields are marked *