Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Pieter Bracke
Pieter Bracke
4,078 Points

Fetched data from database (Mysql) not showing in browser when echod out

I am having an issue with a variable I have stored from my database. It concerns variable $username which has data fetched with a while loop from my DB in it. However when I try to display $username on my HTML page it shows the button witouth the fetched data in it. What am I doing wrong here?

<?php 
session_start();
require_once('connect.php');

if(isset($_POST) AND !empty($_POST)){
    $emaillogin = mysqli_real_escape_string($connection, $_POST['emaillogin']);
    $passwordlogin = md5($_POST['passwordlogin']);

    $sqllogin = "SELECT * FROM `login` WHERE (Email = '$emaillogin' OR Username = '$emaillogin') AND Password = '$passwordlogin'";

    $resultlogin = mysqli_query($connection, $sqllogin);
    $count = mysqli_num_rows($resultlogin);

    if($count == 1){
        $_SESSION['user'] = $resultlogin;
        while($row = mysqli_fetch_array($resultlogin, MYSQLI_ASSOC)){
        $username = $row['Username'];


    }
        $url = "index.php";
        $messageok = "User login succesfull!";
        echo "<script type='text/javascript'>alert('$messageok');</script>";
        echo '<script>window.location = "'.$url.'";</script>';
    }else{
        $url = "index.php";
        $messagenok = "User login failed!";
        echo "<script type='text/javascript'>alert('$messagenok');</script>";
        echo '<script>window.location = "'.$url.'";</script>';
    }
}


?> 
<div id="myLeftRow" class="leftrow" style="display: inline-block;">
    <div class="leftrow-row"> 
<?php

    if(isset($_SESSION['user'])){

            echo "<button onclick='profilelink()' class='button' id='profilebutton'>$username</button>";

            echo "<form method='POST' action='includes/logout.php'><button type='submit 'class='button' id='logoutbutton'>Logout</button></form>";
            echo $username;
    }
    else{ 

            echo "<button onclick='logintoggle()' class='button' id='loginbutton'>Login</button>";

            echo "<button onclick='registertoggle()' class='button' id='registerbutton'>Register</button>";
    }
?>
        <img onclick="togglemenu()" id="myHamburger" class="hamburger-menu" src="images/hamburger.png" />

</div>
Patrik Horváth
Patrik Horváth
11,110 Points

as first never use md5 there are on internet a lot of md5 databases so its not secure

can you var_dumb($row['Username']) ? or var_dumb($row) to see if code go there :) and post your resolt

whot about use this while loop :

while($row = mysqli_fetch_array($resultlogin))

also remmeber DRY :)

$url = "index.php";
        $messageok = "User login succesfull!";
        echo "<script type='text/javascript'>alert('$messageok');</script>";
        echo '<script>window.location = "'.$url.'";</script>';

10 Answers

Patrik Horváth
Patrik Horváth
11,110 Points

got it problem was your styling ... hard to see your { } this why i think problem is somewhere else

and your problem is you store information into $variable and its get DELETED when you realod PAGE so store it in $_SESSION['usr'] for example :)

problem part and when you relocato to another page you lose this data :

$username = $row['Username'];

why data lost ? becaus this code part :

echo '<script>window.location = "'.$url.'";</script>';
Pieter Bracke
Pieter Bracke
4,078 Points

Hmm I var dumped $row and $row['Username'] result is NULL.

Patrik Horváth
Patrik Horváth
11,110 Points

you var_dumb inside IF statment ? if yes so your $count have 1 so you have to have something in variable $row try give it to REAL WEB SERVER, because sometimes Apacher or any other servers cant handle Database connections ( tesed on my self few projects on real server it worked Perfect but on Apache or XAMP it doesnt worked )

or try my while loop

while($row = mysqli_fetch_array($resultlogin))

or use TRY and CATCH blocks to see if there is no hidden errors

Pieter Bracke
Pieter Bracke
4,078 Points

I used your while loop. And I var_dumped in

<?php
    var_dump($row);
    if(isset($_SESSION['user'])){

            echo "<button onclick='profilelink()' class='button' id='profilebutton'>$username</button>";

            echo "<form method='POST' action='includes/logout.php'><button type='submit 'class='button' id='logoutbutton'>Logout</button></form>";
            echo $username;
    }
    else{ 

            echo "<button onclick='logintoggle()' class='button' id='loginbutton'>Login</button>";

            echo "<button onclick='registertoggle()' class='button' id='registerbutton'>Register</button>";
    }
?>

Now I get NULL

If I var_dump in the IF statement that compares the count I get nothing Also the $_SESSION is set because I can log in and out that works really good but I just want to display the username from the logged in person in the button when the person is logged in :)

Patrik Horváth
Patrik Horváth
11,110 Points

so we got it :) "If I var_dump in the IF statement that compares the count I get nothing" so your QUERY found 0 resoults :) fix your query or maybe fix your PDO / MySQLi connection info :), for this always use TRY and CATH and throw error if somethings is wrong and die connection

also why you use ` in table name ?

Pieter Bracke
Pieter Bracke
4,078 Points

I learned to select table name between `` is this not correct?

Patrik Horváth
Patrik Horváth
11,110 Points

i m not 100% sure but never saw it before i use it only in WHERE x = '$a' better remove it :) but on variable it have to be

i think ' ' is where you calling $variables only and compare to string " "

Pieter Bracke
Pieter Bracke
4,078 Points

Also my query should work because I can log in and log out, if my query $resultlogin would not work then I would get NULL for $count also and I would not be able to set a $_SESSION but it does set a $_SESSION it logs in and gives me the login suceeded message. That's why I am so confused

Patrik Horváth
Patrik Horváth
11,110 Points

Simple take a closer look to your code this part always execute if you type any username / passpowrd ... this is why :)

$url = "index.php";
        $messageok = "User login succesfull!";
        echo "<script type='text/javascript'>alert('$messageok');</script>";
        echo '<script>window.location = "'.$url.'";</script>';
Patrik Horváth
Patrik Horváth
11,110 Points

fix it to

if($count == 1){
        $_SESSION['user'] = $resultlogin;
        while($row = mysqli_fetch_array($resultlogin, MYSQLI_ASSOC)){
        $username = $row['Username'];

        $url = "index.php";
        $messageok = "User login succesfull!";
        echo "<script type='text/javascript'>alert('$messageok');</script>";
        echo '<script>window.location = "'.$url.'";</script>';
    } else {
        $url = "index.php";
        $messagenok = "User login failed!";
        echo "<script type='text/javascript'>alert('$messagenok');</script>";
        echo '<script>window.location = "'.$url.'";</script>';
}
Pieter Bracke
Pieter Bracke
4,078 Points

That doesn't makes sense right that code will only execute if count = 1 and for count to equal 1 the mysqli_num_rows has to be = 1 and that will only work if the query $ resultlogin provides only 1 result. When I got rid of the `` around login I did get a result from my query in the if statement btw.

Also If I use the code you posted above the PHP crashes and the whole page is blank so there is an error there 2 :p

Pieter Bracke
Pieter Bracke
4,078 Points

Also if I try to login with a username and pass that is not in my DB it does not work so it does not give the succesfull message with any user or pass

Patrik Horváth
Patrik Horváth
11,110 Points

your code checking this code below check it you will see :)

if(isset($_POST) AND !empty($_POST)) this is true then RETURN "User login succesfull!"

it doesnt metter if your QUERY have 1 or 0 resoults it runs anyways :)

Pieter Bracke
Pieter Bracke
4,078 Points

then why do i get user login failed if I type in wrong username or password?

Pieter Bracke
Pieter Bracke
4,078 Points

Jup that fixed it how did you find this exactly?

Patrik Horváth
Patrik Horváth
11,110 Points

i m glad to help you, just reading your code and question again and assuming SQL is Okey :) so problem should be somewhere Else :) and if you redirect to another site all $ will be removed to it defaults but SESSIONS or COOKIES stay alive until you close webbrowser or defive TIMEOUT :) (example kill cookies after 1 mounth )

mark my answere as Best xD, and try to use Comments next time :)

also you can use PHP header to locate to another page its easyer then javascript