registration form not not showing validation error - php

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.

Related

Invalid sql statment

I'm trying to conduct an experiment using a pre-coded project which inside this link here.
I'm using xampp as a web server with mysql. Whenever I run through the authentication page which has this code:
<?php
include_once("zSessionStart.php");
include_once("zConfig.php");
include_once("zDB.php");
$password = $_REQUEST["password"];
$userID = $_REQUEST["userID"];
$isAdmin = false; //is administrator or not
$askDemo = false;
//authenticate the login data from login.php
$query="select userID, isAdmin, askDemo from $_usersTable where (password= '$password') and (userID='$userID');";
$rs=mysql_query($query) or die ("Invalid sql.");
if ( mysql_num_rows($rs) > 0 ) //correct password
{
$array = mysql_fetch_array($rs);
if(strcmp($array["isAdmin"], "y")==0){
$isAdmin=true;
}
if(strcmp($array["askDemo"], "y")==0){
$askDemo=true;
}
if(!$isAdmin){
$query="select userID from usertests where userID='" . $userID . "'";
$rs2=mysql_query($query) or die ("Invalid sql.");
if(mysql_num_rows($rs2) > 0){ //already take test
$array2 = mysql_fetch_array($rs2);
echo "<h2> You have already taken the task. Please contact your administrator if you " .
" feel you need to re-take this task again.</h2>";
die();
}
}
$_SESSION['userID'] = $array["userID"];
session_unregister('loginErr');
if($isAdmin){
header("Location: transfer.php?" . SID);
}else{
if($askDemo){
header("Location:demo.php?" . SID);
}else{
header("Location: index.php?" . SID);
}
}
}
else
{
$_SESSION['loginErr'] = "true";
header("Location: login.php");
}
mysql_close($db);
?>
I receive an error that says "Invalid sql.". Inside my database I have a table called users which has credentials such as userID and password. I've already set the username to be admin and password to be pass. However, I haven't had any luck figuring out what the issue might be.
Your Query is invalid because you are using wrong table name that is even no variable syntax i.e. $_usersTable. And also you are ending your query with multiple semi colons and even single/double quotes are not properly used.
You need to update your select query like below to resolve your issue:
$query="select userID, isAdmin, askDemo from usersTable where password = '".$password."' and userID ='".$userID."';
I strongly recommend you to use MySqli Prepared Statement Query to make it more Secure like below:
$mysqli = mysqli_connect($host, $username, $password, $db);
$query = "SELECT userID, isAdmin, askDemo from `usersTable` WHERE userID=?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("i", $userID);
$stmt->execute();
$res = $stmt->get_result();
$data = $res->fetch_all();
To learn more about it, follow link http://php.net/manual/en/mysqli.prepare.php

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!";
?>

Error Message not working for PHP user check

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.";
}

PHP/MySQL mysql_num_rows not returning values

I'm new to PHP and programming in general, but am working on doing a login. I've got the signup page completed, and my database populates the records fine. However, when this code gets output it says I have 0 rows from the mysql_num_rows($result);... when, it should be coming back successfully showing 1 row when I input the correct username/password. Whether I put in a successful user/pass combo or not, it outputs the same.
I appreciate any help you can provide, code is listed below:
$SQL = "SELECT * FROM account WHERE username = $username AND password = md5($password)";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
echo $result;
echo $num_rows;
// CLOSE CONNECTION
mysql_close($db_handle);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($result) {
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $num_rows;
EDIT: Complete rewrite
Try this:
<?php
$host = "host";
$user = "user";
$password = "password";
$database = "database";
$username = 'jack'; /* Insert $_Post [''] here with username variable you pass. You could sanitize and validate with for example filter_var (), clean (), etc */
$password_user = 'password from jack'; // same here.
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE{
$query = "SELECT * FROM account WHERE username ='$username' AND password = md5('$password_user')";
$result = mysqli_query($link, $query);
$num_rows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($row) {
session_start();
$_SESSION['login'] = "1"; // pleae not that 1 is converted into a string value
$_SESSION['username'] = $username; // added username, just to test.
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $error_message;
}
// CLOSE CONNECTION
mysqli_close($link);
}
?>
Sample data:
CREATE TABLE account (
id INT auto_increment primary key,
username VARCHAR(30),
password VARCHAR(50)
);
INSERT INTO account(username, password)
VALUES
("bob", md5('password from bob')),
("jack", md5('password from jack')),
('joe', md5('password from joe'));
SQL FIDDLE DEMO
Sample page1
<?php
session_start();
$login = $_SESSION['login'];
$username = $_SESSION['username'];
echo '<h1>It WORKS, <i>'.$username.'</i>!!!</h1>';
?>
Important to note is that I have used the MYSQLI library instead of the MYSQL library. If you have more than one column in you table you should select your output per column. For example, $result['id'].
I found that you didn't escape variable in and out in you SQL statement. I have to note that I didn't debug the part below COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS. I think you can manage that on your own.
W.R.T. the santization and validation you have to do some more work. I don't know how you data is past via the user login in form. Let say you will use POST. In that case you can start at the top of you page with first retrieving all the posted variable using $_POST. Then filter them to make sure you code in is not open for SQL injection. E.g. $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);

Categories