Jump to content

[SOLVED] PHP Variable not showing value issue


AKalair

Recommended Posts

Hi,

I've just started learning PHP and wrote a really basic log in script. But when I log in it says Welcome $name rather than admin. I cant see the problem can anyone hekp me? Thanks

<?php

 

$name = $_POST['name'];

$password = $_POST['password'];

 

if ($name == admin && $password == password)

 

{

 

echo 'Welcome back. $name';

 

}

 

 

else

{

echo 'Bad password or user name';

}

 

 

 

?>

 

Link to comment
Share on other sites

Your particular problem is that variables inside single quotes are not parsed. They are treated as literals. Variables inside double quotes are parsed. As an illustration, try running this:

 

<?php
$foo = 'bar';
echo '$foo'; //echos $foo
echo '<br />';
echo "$foo"; //echos bar
echo '<br />';
echo $foo; //echos bar
?>

 

You have a few options to solve your problem. The two most useful are to either replace those single quotes with doubles:

 

echo "Welcome back. $name";

 

Or to use single quotes and some concatenation (joining, if you prefer):

 

echo 'Welcome back. '.$name; //the . operator is the concatenation operator

 

As to which you chose, it's largely a matter of personal preference. There is a very very slight increase in performance by using single quotes, since the text inside the quotes need not be parsed. For all practical applications, the difference wouldn't be noticeable, however.

 

There is also a further problem with your script in this line:

 

if ($name == admin && $password == password)

 

The strings admin and password should be contained in quotes - all strings should. Unquoted strings are what are called constants. You can read more about those here. The php engine isn't stupid, however. If it finds an undeclared constant, it assumes that you mean to use the string. However, depending on your error reporting level, you could receive a notice. And it's bad practice to not quote your strings. Therefore, the line should be:

 

if ($name == 'admin' && $password == 'password')

 

p.s. Welcome to the forums.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.