1

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 mij DB in it. However when I try to display this var on my HTML page it turns up blank what am I doing wrong here?

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

if(isset($_POST) AND !empty($_POST)){
    $emaillogin = $_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)){
        $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 class='button' id='profilebutton'>".$username."</button>";

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

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

            echo "<button onclick='registertoggle()' class='button' id='registerbutton'>Register</button>";
    }
?>
Qirel
  • 25,449
  • 7
  • 45
  • 62
Pieter
  • 359
  • 3
  • 14
  • If your html code in on other page, you need to pass the username either by query string ( if redirecting) or through sessions. – Ravinder Reddy Sep 18 '17 at 19:33
  • it's in the same filepage as the PHP code and it both gets included to the index page would that cause an issue? – Pieter Sep 18 '17 at 19:39
  • For one, you should group the conditions. `something AND other OR final` will give false positives. Is the entire page blank, or just no value for the username? – Qirel Sep 18 '17 at 19:41
  • 1
    Using old methods of encrypting passwords (such as `sha1`, `md5`) are **poor methods of hashing** - you should use newer methods for hashing your passwords. PHP has a built-in [`password_hash()`](http://php.net/manual/en/function.password-hash.php) function which is a lot more secure! – Qirel Sep 18 '17 at 19:42
  • You're already using an API that supports **prepared statements** with bounded variable input, you should utilize parameterized queries with placeholders (prepared statements) to protect your database against [SQL-injection](http://stackoverflow.com/q/60174/)! Get started with [`mysqli::prepare()`](http://php.net/mysqli.prepare) and [`mysqli_stmt::bind_param()`](http://php.net/mysqli-stmt.bind-param). – Qirel Sep 18 '17 at 19:42
  • @Qirel I am simply stating that if the input is either the username or the email it should be considered valid.. don't see how that can conflict my specific code here Also I am just trying to get the username into button can someone help me with instead of suggesting a million other things :p It's hard enough to grasp this as it is if people constantly say change this and that and that it becomes impossible :p – Pieter Sep 18 '17 at 19:47
  • `Email = '$emaillogin' OR Username = '$emaillogin' AND Password = '$passwordlogin'` should be `(Email = '$emaillogin' OR Username = '$emaillogin') AND Password = '$passwordlogin'`, notice how it's been grouped to avoid false positives (which might actually be your current issue!). And the feedback given in the comments here are security concerns, which you really should take to heart. I get that it might be a lot to take in at once, but it's very important that you try to understand what's being said, and not just get tunnelvision on your issue. – Qirel Sep 18 '17 at 19:50
  • @Qirel Ok, well I am going to use password_hash() later on and lose the md5 but for now I just wanted to be able to use the data which I fetched from my database in my HTML, however it doesn't show anything inside my button. The solution suggested by the guy beneath doesn't work either. You got any idea what might be the issue? – Pieter Sep 18 '17 at 19:58
  • Well, let's do some basic debugging. First, did you change the query to have parenthesis to group the conditions in the `WHERE` clause, as shown in my comment above? Second, do you enter the `if(isset($_POST) AND !empty($_POST)){` condition (which by the way can be reduced to `if (!empty($_POST))) {` - you don't need both, and you should use `&&` instead of `AND` if you so chose to check redundant). – Qirel Sep 18 '17 at 20:33
  • Does the `logintoggle()` JS function do anything? Check your console in the browser for any JS errors. – Qirel Sep 18 '17 at 20:34
  • yes those are seperate js files which toggle a popupscreen they have nothing to do with the login itselfs only changes the style of the page to a pop up – Pieter Sep 18 '17 at 20:54
  • The login itself works perfectly I just want to display the username in the button when the login is completed and that just won't work for some weird reason tried al the solutions given here still not working – Pieter Sep 18 '17 at 20:59

2 Answers2

0

I would first recommend that instead of using

echo '<script>window.location = "'.$url.'";</script>';

just use:

header("Location: ../index.php");`

in the if-statement if you are going to that page.

Under the echo where you have the $username, you have:

echo "<button class='button' id='profilebutton'>".$username."</button>";

When you should just use:

echo "<button class='button' id='profilebutton'>$username</button>";

As you have the username saved to a variable then you don't need the dot before and after. It is only when if you where doing $row['username'] that you would needed to have the dot before and after, because then you are showing raw data from the database.

But otherwise search for where the error can be.

Try to make the the a completely new file, and write it all again:

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

$sqlLogin = "SELECT * FROM login WHERE id=#"; // Just change the # to the id of the user.
$resultLogin = mysqli_query($connection, $sqlLogin);
if(mysqli_num_rows($resultLogin) > 0){
  while($row = mysqli_fetch_array($resultLogin)){
    //Setting the username as the username from the database
    $username = $row['username'];
    // Setting the session['user'] to $username.
    $_SESSION['user'] = $username;
  }
  echo $username;
}
?>

If that doesn't work, then check so that you are putting the name of the entities from the database is correctly spelled. If a letter is big, then it need to be big. Sometimes it is just a small typo as that.

Cordux
  • 1
  • 7
  • yeah when I use header It conflicts and won't work something with whitespace after the php syntax :/ real weird so I fixed it that way I'll give it a go withouth the .. seems weird cause i did used the dots to display another var and that did work .. – Pieter Sep 18 '17 at 19:28
  • It all depends on if the page you are going back to is in the same folder. If it is then don't use ../. Just use index.php. ..// points to go up one directory. – Cordux Sep 18 '17 at 19:33
  • That didn't fix it removing the points and putting the whole string between quotes as you said :/ – Pieter Sep 18 '17 at 19:35
  • yeah I am aware of the ../ syntax :p – Pieter Sep 18 '17 at 19:36
  • That is strange. I took your code and tried it for myself. I pointed $username to a $_SESSION['username'] with making the session to Admin. It works. It shouldn't be any problems with it. What server are you using btw? – Cordux Sep 18 '17 at 19:53
  • I am using Localhost MAMP and PHPmyadmin for the database – Pieter Sep 18 '17 at 20:00
  • Could you perhaps embed the code you used how you pointed $username to $_SESSION so I can double check it – Pieter Sep 18 '17 at 20:01
  • Added! And if you don't want to point it to the username from the database, then you can just use $_SESSION['user'] = "admin"; – Cordux Sep 18 '17 at 20:26
0

Well I have managed to figure it out my syntax was correct but by using the window.location instead of header right here

echo '<script>window.location = "'.$url.'";</script>';

It caused all my variables to be deleted after redirecting from page to page I have no idea why though... Very weird

Pieter
  • 359
  • 3
  • 14