Error Message not working for PHP user check - php

I am new to PHP and have wrote a register PHP page, it is working fine and can add to database for new users. But when adding repeated username, the error message does not appear. did i miss out any codes or do i need to change the codes?
My Code:
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'login');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
function NewUser()
{
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$query = "INSERT INTO users (username, password, firstname, surname) VALUES ('$username', '$password', '$firstname', '$surname')";
$data = mysql_query ($query)or die(mysql_error());
if($data)
{
echo "YOUR REGISTRATION IS COMPLETED, YOU CAN SIGN IN NOW";
}
}
function SignUp()
{
if(!empty($_POST['username']))
{
$query = mysql_query("SELECT * FROM users WHERE username = '$_POST[username]' AND password = '$_POST[password]'") or die(mysql_error());
if(!$row = mysql_fetch_array($query) or die(mysql_error()))
{
newuser();
}
else
{
echo "SORRY, YOU ARE ALREADY REGISTERED USER.";
}
}
}
if(isset($_POST['submit']))
{
SignUp();
}
?>

Since you are new, you might as well ditch the MySQL_ statements and go with something more secure like MySQLi_ or PDO. This won't disallow you to use databases, they are just more secure.
Also: $row is undefined.
And once again, because you are new, I suggest using an editor that gives you indentation to your code. Indentation makes your code more readable, and helps other people help you when you have problems like this.

$row is undefined and try using mysql_num_rows
when ever you want to access the column values you can use mysql_fetch_array
here in this case you just checking for $query returned a row or not.
so you can change you code to
as you did it for
$data = mysql_query ($query)or die(mysql_error());
if($data)
{
echo "YOUR REGISTRATION IS COMPLETED, YOU CAN SIGN IN NOW";
}
$query = mysql_query("SELECT * FROM users WHERE username = '$_POST[username]' AND password = '$_POST[password]'") or die(mysql_error());
if($query){
newuser();
}else{
echo "SORRY, YOU ARE ALREADY REGISTERED USER.";
}

Related

If i login with a user it logs in with any password

<?php
require 'includes/common.php';
$email=$_POST['email'];
$password=$_POST['password'];
$email= mysqli_real_escape_string($con, $email);
$password= mysqli_real_escape_string($con, $password);
//md5($password);
$select_user_query="select id , email from users where email='$email' and password= $password";
//removed 'email' to email//
$select_user_result= mysqli_query($con, $select_user_query) or die (mysqli_error($con));
if (mysqli_num_rows($select_user_result==0))
{
echo 'There no such user ';
}
else
{
$row=mysqli_fetch_array($select_user_result);
$_SESSION['email']=$email;
$_SESSION['id']= $row[0];
header('location:products.php');
}
?>
here is the code
**
here i am geting
email and password from post method
From my login page
i think most of the code is right
If i login with a user it logs in with any password
**
Your error is not in the query. it is on your condition
if(mysqli_num_rows($select_user_result) == 0){
echo 'No User found';
}else{
echo 'oK';
}
You ca try this way. I think your error is you inserted the ==0 inside the mysqli_num_rows() it must be outside.
I'm assuming password is a string..
$select_user_query="select id , email from users where email='$email' and password= $password";
is what you wrote,
you've maybe forgotten to put single quotes around $password here.
Please verify this code:
I use this code for login:
if user provides the Correct Credentials-- If part will work,
if not then else part will be work
<?php
// Grab User submitted information
$user = $_POST["username"];
$pass = $_POST["password"];
//$uc_id=$_GET["user_check_id"];
// Connect to the database
$con = mysqli_connect("localhost","root","pass123");
// Make sure we connected successfully
if(! $con)
{
die('Connection Failed'.mysql_error());
}
// Select the database to use
mysqli_select_db($con, "login");
//$query ="SELECT user_check_id from loginpage where username='$user' and password='$pass'";
$query ="SELECT * from loginpage where username='$user' and password='$pass'";
//echo $query;
if ($query)
{
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result);
if($row["username"]==$user && $row["password"]==$pass)
{
echo "Welcome Admin";
}
else
{
echo"Please Enter the Correct Username/Password...!!";
}
}
?>
Put single quotes around $password in your query and then try.

PHP login code error with mysql_query()

I've been following a login system tutorial. You can find it here. There are 2 parts of coding C# and PHP. The C# part is working fine but my PHP part returning error. Here is my PHP code:
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$passwordp = "";
$database = "game_database";
$dbport = 3306;
// Create connection
mysql_connect($servername, $username, $passwordp, $dbport)or die("Cant Connect to server");
mysql_select_db($database) or die("Cant connect to database");
// Check connection
$Email = $_REQUEST["Email"];
$Password= $_REQUEST["Password"];
if (!$Email || !$Password){
echo"Email or password must be used";
}
else{
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
$result_id = #mysql_query($SQL) or die("Database Error");
$Total = mysql_num_rows($result_id);
if ($Total){
$datas = #mysql_fetch_array($result_id);
if (strcmp($Password, $datas["Password"])){
$sql2 = "SELECT Characters FROM users WHERE Email = '" . $Email ."'";
$result_id2 = #mysql_query($sql2) or die("Database Error!!!");
while ($row = mysql_fetch_array($result_id2)){
echo $row ["Characters"];
echo ":";
echo "Success";
}
}
else{
echo "WrongPassword";
}
}else {
echo "NameDoesNotExist";
}
}
?>
It seems the error comes from $result_id but I'm not sure?
You are true, the error is from $result_id, because your SQL statement has problem and there are extra stuff to fix.
You have put users table in two single quotes, it is wrong.
Your code is:
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
It should be with out quotes:
$SQL = "SELECT * FROM users WHERE Email = '" . $Email ."'";
You have wrote:
if ($Total){
It should check how many users record found, typically it should find only 1 record and return 1, therefore change it to:
if ($Total == 1){
Note1:
But when this is said, it does not mean the code is perfect, you should further develop your code to fulfill nowadays requirement. I would suggest you think of password hashing, use mysqli or PDO in sted of mysql and input sensitization. I would suggest you look at this link it describes some of the things I mentioned.
Note2:
I was able to write you a total solution with mysqli/PDO etc, but I wanted only to point the errors I have catch so far in your code so you can learn from your mistakes and develop your self.
And in general read about security principles, check this page.
Link1: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Link2: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
This is another simple way where you can create user log in, it is
more secure than the one you have at the moment. And you should
protect your code from sql injections.
<?php
if (isset($_POST['email'], $_POST['password']) === true )
{
require 'connection.php';
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$sql = "SELECT * FROM users WHERE email= '$email'";
$result = mysqli_query($connection,$sql);
if (mysqli_num_rows($result))
{
if( $email == $row['email'] && $password == $row['password'])
{ //use session to check if user is logged in
if (!isset($_SESSION['loggedin']))
{
//you can set session of user's log in details
//you can redirect to user profile
}
else
//already log in, redirect to user profile
}
else
echo "Incorrect Email or Password.";
}
else
echo "Incorrect Username or Password.";
mysqli_close($connection);
}
else
{
echo "Oops, something went wrong!";
?>

PHP code always shows wrong result

I am learning PHP and able to create a Registration form. But the code doesn't working properly. It always goes to else statement of Username exists Try Again. Any help appreciated and any explanation greatly welcomed :)
function session() {
$usn = $_POST['username'];
$pwd = $_POST['password'];
$email = $_POST['Email'];
$con=mysqli_connect("********","***********","**********","*********");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Accounts
WHERE username = '$usn'");
If($result == Null) {
mysqli_query($con,"INSERT INTO Accounts (username, password, Email)
VALUES ('$usn', '$pwd','$email')");
$result = mysqli_query($con,"SELECT * FROM Accounts WHERE username = '$usn'");
while($row = mysqli_fetch_array($result)) {
if (($row['password']==$pwd) and ($row['Email']==$email)) {
echo "Registration Success";
}
else {
echo "Registration Failed";
}
}
}
else {
echo "Username Exists Try Again";
}
mysqli_close($con);
}
$result will never be null. You need to check for something like number of rows -
$row_cnt = mysqli_num_rows($result);
If that is greater than 0, then go to your else.

mySQL statement not working inside of php

Im trying to do a login system for my website and I changed around how it is implemented and it broke, whenever I try to login with a correct login it fails to take me to the next page, here is my php:
<?php
//finds the correct database
$sql_link = mysqli_connect("localhost", "root" , "12buckle", "GameData");
if (mysqli_connect_errno())
{
echo "Failed to connect to databse: " . mysqli_connect_error();
}
if (isset($_POST['Username']))
{
$username = mysql_real_escape_string($_POST['Username']);
$password = mysql_real_escape_string($_POST['Password']);
//checking to see if password and username can be found in student database
//loading in correct data
$login = mysqli_query($sql_link,"SELECT * FROM tblStudents WHERE UserName='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['StudentFirstName'];
$_SESSION['ClassID'] = $login['ClassID'];
$_SESSION['ID'] = $login['StudentID'];
header ("Location: index.php");
}
else
{
$login = mysqli_query($sql_link,"SELECT * FROM tblTeacher WHERE Username='$username' AND Password='$password'");
if ($login['Password'])
{
$_SESSION['name'] = $login['TeacherSurname'];
$_SESSION['title'] = $login['Title'];
$_SESSION['ID'] = $login['TeacherID'];
header ("Location: TeacherSide.php");
}
else
{
echo 'Login details incorrect';
}
}
}
Also if it helps when I ran it last night im sure it worked, but I was half awake so I may have been testing the old version
Your logic is faulty. mysql_query returns a result HANDLE. it does not return any actual data. You need to fetch a row first, before checking for actual data:
$result = mysqli_query($sql_link, "SELECT * FROM tblStduents ....");
if (mysqli_num_rows($result) > 0) {
... got a student record
$row = mysqli_fetch_assoc($result);
echo $row['StudentFirstName'];
} else {
... no student rows, repeat with teachers
}
I've had issues in the past where variables aren't read properly the way you have them in your SQL statements.
Try Username='" . $username . "' AND instead and see what happens.

registration form not not showing validation error

I am having issues getting the error to appear when a user is entering a user name that is already taken.
In the code below the database is updated when successful entry is made. However, when an entry is made with a duplicate user name, the entry is placed in the database and no error message is shown. I have looked on the net and tried a few methods and this what I have so far. Thank you for taking a look :)
<?php
// Create connection
$con = mysqli_connect('172.16.254.111', "user", "password", "database"); //(connection location , username to sql, password to sql, name of db)
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} //sql syntax below, first line is collumn titles on the db and second line is values from the html document
//$_post is a form of sending information in php
{
$username = strip_tags($_POST['username']);
$password = md5(strip_tags($_POST['pass']));
$password2 = md5(strip_tags($_POST['pass2']));
$fullname = strip_tags($_POST['fullname']);
$email = strip_tags($_POST['email']);
$department = strip_tags($_POST['department']);
if ($password != $password2) //password doestn equal same as password 2 then the message below is displayed (working)
{
echo "<H2>password doesn't match</H2>";
}
$usercheck = "SELECT * FROM Users WHERE username=$username";
$usercheck2 = mysql_query($usercheck);
if (mysql_fetch_assoc($usercheck2)) {
echo "<H2>This username already exists, please pick another</H2>";
} else {
$sql = "INSERT INTO Users(username, password, password2, email, fullname, department)
VALUES('$username','$password','$password2','$email','$fullname','$department')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "<H2>Registration was successful, please use the access console above</H2>";
}
}
?>
Excuse any comments in the code; I am a beginner at PHP and coding in general.
You're missing some quotes. Try this:
$usercheck = "SELECT * FROM Users WHERE username = '$username'";
// ----------------------------------was missing---^---------^
$usercheck2 = mysql_query($usercheck);
if (mysql_num_rows($usercheck2)) {
echo 'user exists';
}
Also, you shouldn't be using the mysql_* functions. Look into using PDO
Change $usercheck = "SELECT * FROM Users WHERE username=$username";
for this $usercheck = "SELECT * FROM Users WHERE username='$username'"; And tell me if it works.

Categories