Why my programe is not going into the if loop in php - php

I wanted to make a simple login page using php and mysql database where I have created table members (id, username, password).
When I run my program, it's not entering the if block and directly moving to else block
<html>
<body>
<form method="POST" action="process.php">
Username:
<input type="text" name="username">
Password:
<input type="password" name="password">
<input type="submit" value="Login">
</form>
</body>
</html>
My PHP code is
<?php
include("includes/dbConnect.php");
$username=$_POST['username'];
$password=$_POST['password'];
$username=stripcslashes($username);
$username=stripcslashes($password);
$username=$conn->real_escape_string($username);
$password=$conn->real_escape_string($password);
//query
$sql="SELECT * FROM members WHERE username='$username' AND password ='$password'";
$result= $conn->query($sql);
$row=$result->fetch_assoc();
if($row['username']==$username && $row['password']==$password)
{
echo "Welcome";
}
else
{
echo "fail";
}
?>
Please help me out and rectify my error
P.S. I am new to php code so if anyone would like to give me any advice It will be most welcome

Your second line here:
$username=stripcslashes($username);
$username=stripcslashes($password);
is mistakenly assigning to the $username variable again.

Related

Blank entry when inserting into mysql (database)

i am trying to create a login and registration page using php and mysql but i met with some problem.
I reference to this video and the code is below (the code is incomplete, i only did for registration).
So the problem is that when i submit an entry using the register side, my database shows a blank record. I tried various method like
$reg = "INSERT INTO usertable (user,pwd) values ('".$user."','".$pwd."')";
but it did not work and when i did this:
$reg = "INSERT INTO usertable (user,pwd) values ('ABC','1234')";
it worked. What should i do to insert entry using the input text?
<?php
session_start();
$conn = mysqli_connect('localhost', 'root', '1234');
mysqli_select_db($conn,'registeration');
$user = $_POST["user"];
$pwd = $_POST["pwd"];
$s = "select * from usertable where user = '$user'";
$result = mysqli_query($conn,$s);
$num = mysqli_num_rows($result);
if($num == 1){
echo"Username Already Taken";
}
else{
$reg = "INSERT INTO usertable (user,pwd) values ('$user','$pwd')";
mysqli_query($conn,$reg);
}
?>
<h2> Register Here </h2>
<form action="index.html" method="post">
<label>Username</label>
<input type="text" name="user" required>
<label>Password</label>
<input type="text" name="pwd" required>
<br><button type="submit"> Login </button>
</form>
A easy way to know what's full SQL query string the program or you have made.
$reg = "INSERT INTO usertable (user,pwd) values ('$user','$pwd')";
echo $reg
It is better use {} to instead of . to insert variable into a string.
$reg = "INSERT INTO usertable (user,pwd) values ('{$user}','{$pwd}')";
To be sure the POST/GET action target is correct,
For your current code I am not sue index.html can handle it, probably it should be $_SERVER["PHP_SELF"]
To understand PHP String Operators, please refer to
https://www.php.net/manual/zh/language.operators.string.php
I found my mistake. I wrote my php and the register table (together in registration.php) however, my form redirects me to index.html. I copied and pasted my php into my index.php (changed the name) and it worked.
Thanks for those who helped me!
<h2> Register Here </h2>
<form action="index.php" method="post">
<label>Username</label>
<input type="text" name="user" required>
<label>Password</label>
<input type="text" name="pwd" required>
<br><button type="submit"> Login </button>
</form>

MySQLi query - php - html form: query line obtained from html form is different from hard-coded query line?

I am building website with a login page. The login page has a html form as shown, the html file is below:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8" />
<title>Login Page</title>
<link rel="stylesheet" type="text/css" href="/my-site/LoginPage/loginPageGraphics.css"/>
</head>
<body>
<form name="frmLogin" method="post" action="/my-site/LoginPage/login.php" accept-charset="UTF-8"/>
<div id="loginField">
<div>
<script type="text/javascript" src="/my-site/LoginPage/loginPageAction.js"></script>
<script type="text/javascript" src="/my-site/database/databaseActions.js"></script>
<p>
<input id="txtUsername" name="username" type="text" placeholder="username"/> <br/>
<input id="txtPassword" name="password" type="password" placeholder="password"/> <br/>
<input id="btnLogin" type="submit" value="Login"/>
<input type="hidden" name="query" value="SELECT ID, Fname, Lname, Username, Password, Type FROM user_accounts WHERE Username='$Username'"/>
</p>
</div>
<div> <!--This div block has no code behind it yet. It is just there for now.-->
<p>
<input id="btnCreateAccount" type="submit" value="Create Account" onclick="createAccount(txtUsername.value, txtPassword.value)"/> <br/>
Create admin account? <input id="chbCreateAdmin" type="checkbox"/>
</p>
</div>
</div>
</form>
</body>
</html>
When the submit button btnLogin is clicked, the form runs a php script, login.php
<?php //this is login.php
$Query = $_POST["query"]; //Query line from html form
$Username = $_POST["username"];
//This 'hard-coded' query is the exact same as the query line from html form
$Query1 = "SELECT ID, Fname, Lname, Username, Password, Type FROM user_accounts WHERE Username='$Username'"; //hard-coded query line
echo $Query;//There is only 1 difference between these two echos. This echo displays "... Username='$Username'"; //$Username is the variable that holds the entered user name
echo $Query1;// While this echo displays "... Username='TylerB'"; //TylerB is the entered username
if($Query === $Query1){
echo "true";
}elseif($Query == $Query1){
echo"true2";
}else{
echo"false"; //this one gets echoed
}
require "../database/dbConnection.php"; //the contents of this file is below. I am using require, as I want this php file to be re-usable.
/* |___> require "DB.php"; //The DB.php file holds the database login info
$conn = new mysqli($host, $user, $pass, $dbName); //Variables specified in DB.php
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($Query);
*/
/*$Query: $result has 0 num_rows
$Query1: $result has 1 num_rows (this is expected)
This information was found via var_dump($results); The lines of codes was removed a little while ago*/
if($result->num_rows > 0){ //If num_rows is equal to 1, no account with the entered username was found
while($row = $result->fetch_assoc()){
if($_POST["password"] === $row["Password"]){//If entered password matchs the selected account's password, login to home page
if($row["Type"] === "Admin"){//Purpose of this if statement is not relevant to the question. Just know, if login info is correct, user logins to a home page.
echo "go to admin home page";
}else{
echo "go to student home page";
}
}else{//if password is incorrect
echo "ERROR: Username or password was incorrect. Please enter the correct account information.";
}
}
}else{//if username is incorrect
echo "ERROR: Username or password was incorrect. Please enter the correct account information.";
}
?>
When I use the variable $Query1, the website runs correctly. However, when I use $Query, $result 's num_rows is 0. In otherwords, it didn't find an account with the username TylerB (despite that $Query1 does find an account with the username TylerB).
The only difference that echos between $Query1 and $Query at the end of the query line: (See top of login.php file for more info about these two variables)
echo $Query;//There is only 1 difference between these two echos. This echo displays "... Username='$Username'"; //$Username is the variable that holds the entered user name
echo $Query1;// While this echo displays "... Username='TylerB'"; //TylerB is the entered username
My questions...
Why are the two query variables giving two different query results? How do I fix this?
I suspect this is mainly revolving around the two slightly different echos for $Query and $Query1. Is the $Username in "... WHERE Username='$Username'" being queried instead of $Username's value? (I doubt this myself...)
If it is, how should I approach this? The query line that dbConnection.php requires needs to come from another source, otherwise it will be specific to the login page. Which is the exact opposite of my intentions - having dbConnection.php re-usable any wheres when a query is needed.
Versions/programs etc:
Sublime 3
Apache web server (all in one package from http://www.wampserver.com/en/ Used WAMPSERVER (64 BITS & PHP 5.6.15 $ PHP 7)
PHP 7
Google Chrome
MySQL
JS
CSS
Windows 10
---------------------------------------------EDIT-------------------------------
While there isn't as much re-usable code as I was going for. I can still work with what I have. However, regarding all the comments around safety and hacking... How safe is this code?
<form name="frmLogin" method="post" action="/my-site/LoginPage/login.php" accept-charset="UTF-8"/>
<div id="loginField">
<div>
<script type="text/javascript" src="/my-site/LoginPage/loginPageAction.js"></script>
<script type="text/javascript" src="/my-site/database/databaseActions.js"></script>
<p>
<input id="txtUsername" name="username" type="text" placeholder="username"/> <br/>
<input id="txtPassword" name="password" type="password" placeholder="password"/> <br/>
<input id="btnLogin" type="submit" value="Login"/>
</p>
</div>
<div>
<p>
<input id="btnCreateAccount" type="submit" value="Create Account" onclick="createAccount(txtUsername.value, txtPassword.value)"/> <br/>
Create admin account? <input id="chbCreateAdmin" type="checkbox"/>
</p>
</div>
</div>
</form>
Submit runs the following...
<?php
$User = $_POST["username"];
require "../database/dbConnection.php";
/* |
<?php
require "DB.php";
$conn = new mysqli($host, $user, $pass, $dbName);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
?>*/
$stmt = $conn->prepare("SELECT ID, Fname, Lname, Username, Password, Type FROM user_accounts WHERE Username=?");
$stmt->bind_param("s", $User);
$stmt->execute();
$stmt->bind_result($ID, $Fname, $Lname, $Username, $Password, $Type);
$stmt->fetch();
if($User === $Username){
if($_POST["password"] === $Password){
if($Type === "Admin"){
echo "go to admin home page";
}else{
echo "go to student home page";
}
}else{
echo "ERROR: Username or password was incorrect. Please enter the correct account information.";
}
}else{
echo "ERROR: Username or password was incorrect. Please enter the correct account information.";
}
?>
My questions was answered in the OP comments, the overall answer is at this link:
MySQLi query - php - html form: query line obtained from html form is different from hard-coded query line?

mysql_query("INSERT INTO... is not working

I'm trying to create a registration page. The page is successfully connected to phpMyAdmin database but it does not echo anything when i click the register button.
<html>
<head>
</head>
<body>
<?php
INCLUDE "connect.php";
INCLUDE "functions.php";
INCLUDE "titlebar.php";
?>
<div id="loginform">
<h1>Register</h1>
<form name="Register" action="register.php" method="post">
<?php
if(isset($POST["submit"])){
$username = $_POST["username"];
$password = md5 ($_POST["password"]);
if(empty($username) or empty($password)){
echo "<p>Fields Empty!</p>";
} else {
mysql_query("INSERT INTO login VALUES('',$username','$password','2','')");
echo "<p>Successfully Registered!</p>";
}
}
?>
<p>
<label for="username">Username: </label>
<input type="text" name="username" id="username"/></p><p>
<label for="password">Password: </label>
<input type="password" name="password" id="password"/></p><p>
<input type="submit" name="submit" value="Register" />
</p>
</form>
</div>
</body>
The problem is with the post method.
use $_POST instead of $POST
You have mysql error
Not: $username'
but '$username'
And next time display mysql errors with mysql_error().
At the beginning, I am not sure what isset($_POST['submit'] should return, but as already mentioned in the comments you missed a single quote.
Additionaly i would use:
$password = password_hash($_POST['password'],
md5 is deprecated and thus not safe. If you write a login script you can use password_verify(plainPW, hashPW)
You also need to specify a database and login into it. I recommend to look at the W3 Schools examples they are very in-depth and have good examples.
W3 school mysqli page
also write a die() at the end of your script and do not foregt to close the connection.

Log in form does not work and i cant find out why

I am trying to make a simple login form but I can not make it work. I have tried different things and searched for answers but nothing seems to be working. When I press the login button nothing happens its like there is no code for it.
here is the code I used:
<?php require 'Connections/Connections.php';?>
<?php
if(isset($_POST['Login'])){
$EM = $_POST['email'];
$PW = $_POST['pwd'];
$result = $con->query("SELECT email, pwd WHERE email=$EM and pwd='$PW'");
$row = $result->fetch_array(MYSQLI_BOTH);
session_start();
$_SESSION["user_id"] = $row['user_id'];
header('Location: account.php');
}
?>
<html>
<head>
<title>Social</title>
<link rel="stylesheet" href="css/signin.css">
</head>
<body>
<div id="form">
<form id ="form1">
<input class="paper" type="email" name="email" id="email" required="required" placeholder="E-mail:"><br>
<input class="paper1" type="password" name="pwd" id="pwd" required="required" placeholder="Password:">
<button name="Login" id="login" value="Submit" type="submit">Login</button>
</form>
<form id="form2" action="register.php" method="get">
<button name="register" id="button2" value="submit" type="submit">Register</button>
</form>
</div>
<!-- <img id="logo" src="logo1.png">-->
</body>
</html>
and here is what the required file has in it:
<?php
$con = mysqli_connect("localhost","root","","phplogin");
?>
First of all, start session at the very top of your PHP script, like this:
<?php
session_start();
?>
Second, add action="post" attribute to your <form> element,
<form id ="form1" method="post">
Third, your SELECT query is also wrong, it should be:
$result = $con->query("SELECT user_id, email, pwd FROM your_table WHERE email='$EM' and pwd='$PW'");
And finally, use ->num_rows to check the number of rows returned by the SELECT query, and use exit() after header() because header() alone is not sufficient to redirect the user to a different page.
Here are the references:
mysqli_result::$num_rows
exit()
So your code should be like this:
// your code
$result = $con->query("SELECT user_id, email, pwd FROM your_table WHERE email='$EM' and pwd='$PW'");
if($result->num_rows){
$row = $result->fetch_array(MYSQLI_BOTH);
$_SESSION["user_id"] = $row['user_id'];
header('Location: account.php');
exit();
}else{
echo "Incorrect user credentials";
}
// your code
You're trying to redirect with the header() function, but because of how you've sectioned off your <?php tags at the top, you're probably getting a suppressed error about headers already being sent. If you clean up the top of your file, the redirect should work:
<?php
require 'Connections/Connections.php';
if (isset($_POST['Login'])){
...

How to validate login form using JavaScript PHP and MariaDb?

I am starting to learn JavaScript today. I want to validate the user login form using JavaScript and MariaDB. I know how to connect to database using PHP, but if I have to do it through JavaScript, is that possible? I
I want to get the user's table using JavaScript. The user will get an error when, of course, their username/password does not match what they have on the database. I am really curious about this.
<form name="loginForm" id="loginForm" method="post" action="login.php" onsubmit="return validateLoginForm();">
Username: <input type="text" name="username">
Password: <input type="password" name="password"> <br/>
<input type="submit" name="login" value="Login"/>
</form>
If the user click the button, will connect to the table using JavaScript. But I dont know how to do it.
Thanks.
I am going to use jquery which is an excellent javascript framework.
Since you have no code to show, I will only post for you pseudo code to show you how you can validate a username and password using jquery,php and mariadb. The mysqli API in php will work with mariadb
HTML\Client side
<html>
<head>
<script src="jquery-1.X"></script>
<script>
$(document).ready(function(e){
var username=$("#username").val();
var password=$("#password").val();
$("#login").click(function(){
if(username=="" && password=="")
{
alert("username or password is blank");
e.preventDefault();//prevent the form from submitting.
}
})
})
</script>
</head>
<body>
<form name="loginForm" id="loginForm" method="post" action="login.php">
Username: <input type="text" name="username" id="username">
Password: <input type="password" name="password" id="password"> <br/>
<input type="submit" name="login" id="login" value="Login"/>
</form>
</body>
</html>
PHP Side - Login.php
<?php
include("conn.php");
$username=$_POST['username'];
$password=sha1($_POST['password']); //my passwords are hashed in the database using the sha1
$checklogin="SELECT * FROM users_tbl WHERE Username=? AND Password=?";
$query = $connection->prepare($checklogin);
$query->bind_param("ss",$username,$password);
$query->execute() or die($connection->error);
$count = $query->num_rows;
if($count==1)
{
while($row=$query->fetch_assoc)
{
$_SESSION['username']=$row['Username'];
}
header("Location:index.php")
}
?>
PHP Connection File - conn.php
<?php
//connect to database
$connection = new mysqli("localhost","user","password","mydatabase");
if(mysqli_connect_errno()){
printf("Connection failed: %s\n",mysqli_connect_error());
exit();
}
?>
Please not this is a very basic login script to give you a general understanding. You need to read up on jquery and PHP in detail.

Categories