1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

User id not displaying in login system

Discussion in 'PHP' started by sash_007, Nov 11, 2019.

  1. #1
    Hello friends,

    I am following a tutorial from youtube to build a login system
    it was written in mysql

    i have converted most parts to mysqli
    but stuck at some point
    i just want echo the user id based on the login
    to check if things are working before i move on to the session part
    but its not displaying the id
    although the login works

    my code for index.php
    SEMrush
    <?php
    require "core.inc.php";
    require "connect.inc.php";
    include "loginform.inc.php";
    
    
    
    ?>
    PHP:
    my code for connect.inc.php

    <?php
    //$conn_error = "could not connect";
    $mysql_host= "localhost";
    $mysql_user = "root";
    $mysql_pass ="";
    $mysql_db ="a_database";
    
    $conn = mysqli_connect($mysql_host,$mysql_user,$mysql_pass,$mysql_db);
    
    /*if(!mysqli_connect($mysql_host,$mysql_user,$mysql_pass) && !mysqli_select_db($mysql_db)){
        die($conn_error);
    }
    */
    if(!$conn){
         die("Connection failed: ". mysqli_connect_error());
    
    }
    
    
    ?>
    PHP:
    my code for
    loginform.inc.php

    <?php
    //ini_set('display_errors','1');
    //error_reporting(E_ALL);
       global $conn;
    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 = mysqli_query($conn,$query)){
            $query_num_rows = mysqli_num_rows($query_run);
            if($query_num_rows==0){
                echo "invalid username/password combination";
            }else if($query_num_rows==1){
    
            echo $user_id = mysqli_fetch_assoc($query_run);
            }
    }
       }else{
           echo "you must fill in the username and password properly";
       }
    }
    
    
    
    
    
    ?>
    <form action ="<?php echo $current_file; ?>" method="POST">
       Username:<input type="text" name="username"> Password:<input type="password" name="password">
    
        <input type="submit" value="Log in">
    </form>
    PHP:

    i think the error is in this line from
    loginform.inc.php
    echo $user_id = mysqli_fetch_assoc($query_run);

    do note i am not looking for object oriented or pdo solution,i know its there

    as i am new to php let me first learn mysqli procedural approach first
    so if you have solution it will be highly appreciated thanks


    I go this working my new loginform.inc.php
    
    
    <?php
    //ini_set('display_errors','1');
    //error_reporting(E_ALL);
       global $conn;
    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 = mysqli_query($conn,$query)){
            $query_num_rows = mysqli_num_rows($query_run);
            if($query_num_rows==0){
                echo "invalid username/password combination";
            }else if($query_num_rows==1){
                $row = mysqli_fetch_assoc($query_run);
            echo $user_id = $row['id'];
            }
    }
       }else{
           echo "you must fill in the username and password properly";
       }
    }
    
    
    
    
    ?>
    <form action ="<?php echo $current_file; ?>" method="POST">
       Username:<input type="text" name="username"> Password:<input type="password" name="password">
       
        <input type="submit" value="Log in">
    </form>
    PHP:
     
    Last edited: Nov 11, 2019
    sash_007, Nov 11, 2019 IP
    SEMrush
  2. sarahk

    sarahk iTamer Staff

    Messages:
    25,465
    Likes Received:
    3,529
    Best Answers:
    102
    Trophy Points:
    665
    #2
    Get used to using filter_input instead of accessing your $_POST variables directly ESPECIALLY when putting them into a database query.

    Have you echo'd out the number of rows?
    Have you echo'd out the query and checked that you get the result you expect if you run it in phpMyAdmin?
    What do you get from a var_dump of $user_id?
     
    sarahk, Nov 11, 2019 IP
  3. sash_007

    sash_007 Active Member

    Messages:
    168
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    75
    #3
    i got this working
    my new login
    thanks i already found a solution posted the update in my first post
     
    sash_007, Nov 11, 2019 IP
  4. SpacePhoenix

    SpacePhoenix Well-Known Member

    Messages:
    129
    Likes Received:
    15
    Best Answers:
    1
    Trophy Points:
    120
    #4
    You must be using quite an old tutorial as md5 is way too weak these days to be used for hashing passwords. PHP now has built in functions (5.4 and newer) for dealing with password hashes (https://www.php.net/manual/en/ref.password.php
     
    SpacePhoenix, Nov 11, 2019 IP
    deathshadow and sarahk like this.
  5. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,107
    Likes Received:
    1,691
    Best Answers:
    239
    Trophy Points:
    515
    #5
    filter_input is pointless trash if you look at the REAL problem here; a problem I'm both shocked and dissapointed nobody is mentioning.

    Slopping the variables into the query string like it's still 2004. It's called prepare/execute, USE IT!

    @SpacePhoenix hitting it on the head with the MD5 as well, though I dislike the PHP password functions given their choice of equally outmoded hashing algo's, and worse than that password_verify requiring a pull from the DB violating the mono-directional good practice for logins.

    I'd also suggest axing the mysqli for PDO since it lets people keep sleazing along with outdated non-object model access. Likewise the global declarations seen unnecessary since there are no functions present to create scoping issues. Likewise a PROPER and COMPLETE form aren't a bad idea, as is storing that the user logged in successfully in a session. I assume somewhere in your index.php or one of the includes you've got a session_start(); and session_regenerate_id(); ?

    ditching the derpy mysqli

    connect.inc.php
    
    <?php
    
    try {
    	$db = new PDO(
    		'mysql:dbname=a_database;host=localhost',
    		'root', // username
    		'' // password
    	);
    } catch (PODException $e) {
    	die ('Connection failed: . $e->getMessage);
    }
    Code (markup):
    login.inc.php
    
    <?php
    
    $loginError = false;
    
    if (
    	!empty($_POST["username"]) &&
    	!empty($_POST["password"])
    ) {
    	$stmt = $db->prepare('
    		SELECT id
    		FROM users
    		WHERE username = ?
    		AND password = ?
    	');
    	$stmt->execute([
    		$_POST['username'],
    		hash('sha512', $_POST['password']
    	]);
    	if (
    		!($_SESSION['user_id'] = $stmt->fetchColumn())
    	) $loginError = 'Invalid Username or Password';
    	$_POST['password'] = ''; // delete to reduce code elevation window
    } else $loginError = 'Username or password were empty';
    		
    if ($loginError) echo '
    	<form action="index.php" method="post" id="login">
    		<fieldset>
    			<legend>Log In</legend>
    			<p>', $loginError, '</p>
    			<label for="login_username">Username:</label>
    			<input type="text" name="username" id="login_username"><br>
    			<label for="login_password">Password:</label>
    			<input type="password" name="password" id="login_password" required><br>
    			<button>Submit/button>
    		</fieldset>
    	</form>';
    
    Code (markup):
    Of course this all assumes that you are storing the user thus:

    
    $stmt = $db->prepare('
    	INSERT INTO users (
    		username, password
    	} VALUES (
    		?, ?
    	)
    ');
    $stmt->execute([
    	$_POST['username'],
    	hash('sha512', $_POST['password'])
    ]);
    
    Code (markup):
    Seriously, ditch the herpaderp mysqli trash for PDO. It's a pain in the ass to work with for prepare/execute (which is the ONLY way you should be putting variables into queries) and allows too many outdated, outmoded, and just plain trash techniques from the older deprecated mysql_ functions to still be used.

    ... and yeah, whatever tutorial you're following is incompetent trash.
     
    deathshadow, Nov 12, 2019 IP
    SpacePhoenix likes this.
  6. sarahk

    sarahk iTamer Staff

    Messages:
    25,465
    Likes Received:
    3,529
    Best Answers:
    102
    Trophy Points:
    665
    #6
    The OP learnt about that last week: https://forums.digitalpoint.com/thr...wing-all-results-instead-of-specific.2860448/
    I'm not sure why that hasn't been incorporated here.

    The OP acknowledges that but has chosen to learn this first.

     
    sarahk, Nov 12, 2019 IP
  7. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,107
    Likes Received:
    1,691
    Best Answers:
    239
    Trophy Points:
    515
    #7
    Then they've chosen to learn how to do it in a wrong, outdated, outmoded fashion DESIGNED to make them screw it up.

    Put on the big boy pants and learn to do it right, instead of the derpy old way.
     
    deathshadow, Nov 12, 2019 IP
    SpacePhoenix and sarahk like this.
  8. NetStar

    NetStar Notable Member

    Messages:
    2,359
    Likes Received:
    501
    Best Answers:
    21
    Trophy Points:
    245
    #8
    The code sucks. Too many people waste valuable time by attempting to bypass the necessary steps it takes to learn programming.

    You should first learn the PHP language by reading simple tutorials so you understand how PHP code works. THEN move on to tutorials on building full applications. Unfortunately, newbies try to skip step one then they ask a MILLION questions about their copy and paste slap together makeshift code and never ever understand what the problem is or even how to fix it. They spend TOO MUCH time with trial and error, asking others to do it for them, or creating more work arounds instead of taking the short period of time it takes to read about the fundamentals of programming and the language.

    Even if you succeed with your task of showing the userid (dead freaking simple if you knew the language for 1 day) you are still left with OLD dated code that is vulnerable to an SQL attack allowing a hacker of elementary skill level to corrupt your entire database and application.

    Crawl. Walk. Run. Try to run first and you will end up on your ass. You are right now on your ass.
     
    NetStar, Nov 12, 2019 IP
  9. sarahk

    sarahk iTamer Staff

    Messages:
    25,465
    Likes Received:
    3,529
    Best Answers:
    102
    Trophy Points:
    665
    #9
    I reckon this is a fine example to learn with but I'm disappointed that the OP hasn't taken what was learnt last week and applied it before asking for help. There's no evidence of debugging or trying different code. The flat refusal to use PDO is naive. Updating the tutorial with knowledge gained would be a good test of his/her new skills.
     
    sarahk, Nov 12, 2019 IP
  10. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,107
    Likes Received:
    1,691
    Best Answers:
    239
    Trophy Points:
    515
    #10
    You realize you just described those frameworks you've been defending, right? :D

    A situation only exacerbated by said "frameworks" being made by people just as hobbled by their methodology as the suckers they take advantage of.
     
    deathshadow, Nov 13, 2019 IP
  11. sash_007

    sash_007 Active Member

    Messages:
    168
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    75
    #11
    omg this thread is turning into battlefield


    i never said i will not learn prepared statement/PDO but the thing is i am in the middle of a tutorial series having 200 videos and i want to finish that first whatever i grasp or i leave that in the middle?
    with due respect to everybody ..you guys are veterans and i am newbie and i accept that
    but please give me some time i will learn all whatever you guys have mentioned

    and this is just for learning purpose i am not gonna use this code for professional use

    and i believe all of you guys also made mistakes at some point of your coding career...right ?
    and we should all learn from mistakes so do I..

    thanks everybody for contributing to this thread
     
    sash_007, Nov 13, 2019 IP
  12. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,107
    Likes Received:
    1,691
    Best Answers:
    239
    Trophy Points:
    515
    #12
    Apologies if you found it all a bit harsh, but what we're trying to tell you is that said video tutorials you are watching are outdated crap you need to STOP watching before you get your head packed full of outdated, outmoded, and improper techniques that should have been killed off two decades ago.

    It is apparent from your code that whatever it is you're following for a tutorial was made by people unfit to teach you any of this. Though IMHO that's the definition of video tutorials. I've never been able to learn a damned thing from that type of instruction!

    ... and it's those mistakes we're trying to prevent you from replicating. We've already screwed this stuff up, the last thing we want to see is someone else get packed full of incompetent ignorant BS from tutorials made by people unqualified to write a single blasted line of HTML, much less tell others how to do so.

    There's nothing more painful than watching others make mistakes you've already learned better than "the hard way".

    Like the outdated, outmoded, half-assed dipshit stuffing of variables into query strings, something we've been told for a decade and a half to stop doing! Yet still brand new tutorials get sleazed onto youtube any-old-way telling people to do that.
     
    deathshadow, Nov 13, 2019 IP
    sarahk likes this.
  13. sash_007

    sash_007 Active Member

    Messages:
    168
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    75
    #13
    it's ok ... please recommend me some good latest version php tutorials(would be better if its video) from beginner to advanced apart from w3schools that teach you beginner to advanced..i will have a look at it..thanks
     
    sash_007, Nov 13, 2019 IP
  14. Spoiltdiva

    Spoiltdiva Prominent Member

    Messages:
    6,569
    Likes Received:
    1,947
    Best Answers:
    51
    Trophy Points:
    395
    #14
    Comparatively speaking I was thinking, "Why is everyone being so laid back on this thread?" This is nothing to what it can be like sometimes on here, welcome to DP.;)
     
    Spoiltdiva, Nov 13, 2019 IP
    sarahk likes this.
  15. NetStar

    NetStar Notable Member

    Messages:
    2,359
    Likes Received:
    501
    Best Answers:
    21
    Trophy Points:
    245
    #15
    No. Most of the major PHP frameworks (ie. Laravel, Symphony, Zend etc) are not slapped together with copy and paste code from newbies. Those systems are written by people who you could learn a lot from (yes you specifically). I would like to go in it with you if you start another thread =)
     
    NetStar, Nov 13, 2019 IP
  16. NetStar

    NetStar Notable Member

    Messages:
    2,359
    Likes Received:
    501
    Best Answers:
    21
    Trophy Points:
    245
    #16
    Just use google. Any beginners tutorial that focuses on the basics is fine.
     
    NetStar, Nov 13, 2019 IP