I want to make simple login server for android.
Login feature works well, but in registration has some problem.
My intent is :
Android Client Send User Info(id, username, password) to XAMPP Server by using HTTPPOST.
Server get User Info, and find repetition id or username from database(using select query). if repetition exists, response to client using echo.
if repetition not exists, make new user info to database using insert query. And response to client using echo.
If repetition exists, it works well. server response correctly.
but in case of no repetition, query's output is 1 then server response 'there is repetition'...
login.php is same code with register.php, but there is no insert query in login.php, and it works perfectly well.
so I think this problem caused by insert query.
here is my code:
<?php
$hostname_localhost ="localhost";
$database_localhost ="mydatabase";
$username_localhost ="root";
$password_localhost ="";
$id_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost, $id_localhost) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$id = $_POST['id'];
$query_search = "select * from tbl_user where username = '".$username."' OR id = '".$id."'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
if($rows == 0) {
$query_register = "INSERT INTO tbl_user (id, username, password) VALUES ('$id', '$username', '$password')";
$result = mysql_query($query_register) or die(mysql_error());
if($result == TRUE){
echo "Register Success";
} else {
echo "Register Fail";
}
exit;
die;
} else {
echo "Registered Device or Username";
exit;
}
?>
login.php is almost same. only search query(select id and username and password same) and insert query is different(no insert in login.php).
server response is wrong but insert action is doing right. I can see new record in my database. so... it seems to be run twice.
client side has no problem because it also almost same with login code(And login works well with no insert query:)).
Update
mysql_num_rows return an int, you are checking if $rows is false instead of 0. Use ===.
What id are you referring to in your tbl_user and why would the user supply their ID? Are you sure that you are checking for the right id? It feels like you should be doing a separate query for the device id OR check for a device_id column in the table tbl_user.
Other things to look into
exit; and die; are the same so calling it twice makes no sense.
if ($rows == 0) is checking for (bool) false instead of the integer 0. Use === for checking for supplied type.
When using "" double-quotation marks you can supply the variables directly;
E.g. "...WHERE username = '$username'" instead of "... WHERE username = '".$username."'".
Look into using mysqli instead of mysql for more features and improved security; http://php.net/manual/en/book.mysqli.php
Related
I'm trying to take input from form and compare to $username in database.
If the username does not exist it should print error.
elseif (($_POST['user']) != ($this->mysqli->query("SELECT * FROM users WHERE username='" . $username . "'"))) {
$json['message'] = "User does not exist";
}
This doesn't log a php error, but it doesn't work either.
Make sure you're receiving the correct username through the POST request, this is a common source of errors. Just log it and check the errors file.
Then, let's analyze your mysql query:
SELECT * FROM users WHERE ...
After the select keyword, you should specify which columns you want to be returned. An asterisk (*) means you want all of them, which is fine if you have a single column, the username, but I'm assuming you have more. In this case, notice in your code that you'll be comparing a bunch of columns against the username. It will fail.
Check out this tutorial, it will be helpful to get familiar with using php plus mysql.
I wrapped the snippet below to show you a way of doing this, there are many. It is just checking if the query returned zero rows, which indicates that no record with the given username exists. A better way would be using the mysql function EXISTS().
$username = $_POST["username"];
error_log("Checking if username:'$username' exists.", 0);
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
$sql = "SELECT * FROM users WHERE username = '$username'";
$query = $conn->query($sql);
if ($query->num_rows == 0) {
error_log("The username does not exist.", 0);
}
So I am trying to develop an app and I need an API, so I am trying now PHP in order to pass my variables from the app to the MYSQL. I am trying with $_GET first in order to see if everything works fine. I tried to pass variables to the database through MYSQL Workbench and then from the app and worked fine. But, when I emptied the table and tried again it didn't work! So I am guessing that my loop doesn't respond well to the fact that my table is empty(?)
This is the code that checks for the email and username if exists and if not insert the variables:
$result = 'notSet';
$query=mysql_query("SELECT * FROM project");
while ($row = mysql_fetch_assoc($query)) {
if(strcmp($row['email'],$email)==0){ //strcmp uses two strings and it returns an integer, if 0 then no differences if more than 0 then there are
$result = 'Email exists';
}else{
if(strcmp($row['username'],$username)==0){
$result = 'Username exists';
}else{
//encryption
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
}
}
Any ideas??
Your table is empty. $query is returning false. Because of this your loop is not executed. You should change the code like this:
if($query){
while(){
//check username and email
}
}
else{
// execute insert query
}
Can you try this code:
$result = 'notSet';
$query = mysql_query("SELECT * FROM project WHERE email = '$email' OR username = '$username' ");
if(mysql_num_rows($query) === 0 ){
$insert = mysql_query("INSERT INTO project VALUES ('$userid', '$fullname','$username','$password','$course','$year','$age','$email')");
$result = 'Registered';
session_start();
$session = session_id();
$SESSION['username']=$username;
}
else{
$result = 'Username or Email exists';
}
We should add single quotes ' only if field type is not integer type. For eg if userid field is integer type and rest of fields are not integer type then query will be
$insert = mysql_query("INSERT INTO project VALUES ($userid, '$fullname','$username','$password','$course','$year','$age','$email')") or die(mysql_error());
thanks
First: you should switch to PDO or mysqli, because the mysql_* functions are deprecated. Please follow the links in Shais comment.
To get the INSERT done, you've got to change your logic. With your code right now, it will never be executed for an empty resultset. You could do it so:
$query=mysql_query("SELECT * FROM project");
if (mysql_num_rows($query) > 0) {
// we've got results, let's loop through the resultset
while($row = mysql_fetch_assoc($query)) {
// do something with the result
}
}
else {
// we've got no results,
// do the insert
}
mysql_query will return a resource for SELECT type queries. A resource evaluates in PHP to true. You can use mysql_num_rows() to check, whether your resultset is not empty.
Excerpt from the linked manual:
Use mysql_num_rows() to find out how many rows were returned for a
SELECT statement
PS: Please consider the content of the red box.
<?php
$query=mysql_query("INSERT INTO project set id=$userid,
'fullname'=$fullname,
'username'=$username,
'password'=$password,
'course'=$course,
'year'=$year,
'age'=$age,
'email'=$email
");
?>
I want to check if the 'desig' (designation) of a user stored in user_info database, is 'gm' (G.M.) or not.
Currently, I have two users, one with 'desig' as 'gm' and the other as 'mgr', no matter who logs in, the 'gm.html' page always loads.
The correct working should be that if the desig is gm then only it should redirect to gm.html page. (members is a table in user_info db)
<?php
session_start();
if((isset($_SESSION['login']) && $_SESSION['login'] ==true)) {echo "";}
else{
header("location:login.html");}
$mysql_hostname = 'localhost';
$mysql_usrnm = 'root';
$mysql_pass = '';
$mysql_db = 'user_info';
$con = mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db) or die('Cant connect to database');
mysqli_select_db($con,$mysql_db);
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
$desig = mysqli_fetch_array($result) or die("error");
if($desig!="gm")
{
$mysql_db1='customer';
$con1=mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db1) or die("Connection died for your sins.");
echo "Connected";}
else
header("location:gm.html");
?>
Your code seems to be hard-coded to only return a GM?
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
I am pretty sure that this is supposed to be picked up based on the user and not simply running a "find me a GM user" for anyone.
If I understand your question correctly, shouldn't there be somewhere in betwen the start and end of this snipped that uses the login information to verify what level a user is it?
if((isset($_SESSION['login']) && $_SESSION['login'] ==true))
{
echo "";
// Shouldn't you run a query here to see who your user is?
// For example to get their ID?
}
else
{
header("location:login.html");
}
$mysql_hostname = 'localhost';
$mysql_usrnm = 'root';
$mysql_pass = '';
$mysql_db = 'user_info';
$con = mysqli_connect($mysql_hostname, $mysql_usrnm, $mysql_pass, $mysql_db) or die('Cant connect to database');
mysqli_select_db($con,$mysql_db);
$result = mysqli_query($con, "SELECT desig FROM members WHERE desig='gm'");
// Then here, instead of running this, convert it to something similar to:
$result = mysqli_query($con, "SELECT desig FROM members WHERE userid=$id");
Edit:
Storing the variable is easy - but you have to GET it from somewhere.
You can do this by popping a column in your users table - where you verify the username and password to begin with. I would suggest you look into a basic table like this to store user information. (I would also recommend you store hashes of passwords and the like, but that seems a conversation for another time).
user table:
userID username password userLevel
1 someUser somePass Grunt
2 someUser1 somePass1 MGR
3 someUser2 somePass2 MGR
4 someUser3 somePass3 GM
Armed with this, you can fire off a quick query to the database, verify the username and password, and get their userLevel quite easily.
Once you have the level, you can store it in a session variable if you like and have your code apply logic depending on what is stored in there.
I fixed the problem. There were some logical errors in my code.
if((isset($_SESSION['login']) && $_SESSION['login'] ==true)) {
//Selecting the whole row to compare and display different variables
$sql = "SELECT * FROM members WHERE username = '".$_SESSION['username']."'";
if(!$sql)
echo mysql_error();
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
//Using $row variable to fetch and compare the value stored in 'desig' with 'gm'
if($row["desig"]=='gm')
header("location:gm.php"); //Opens up different page for gm aka Gen. Mgr.
}
else
header("location:login.html"); //Redirects to this page if no user is logged in.
I am trying to create a login form in PHP. i am passing the username and password that user had entered and check weather that exist in the data base.
i have done the coding, but IF EXIST query does not return any result.
can any one help me to fix this. or give me a alternate idea.. Thank you...
<?php
$name= $_POST["usname"];
$pass = $_POST ["password"];
$connection = mysqli_connect("localhost","sathya","sathya","learning1");
//mysqli_query($connection,"INSERT INTO user (name, password) VALUES ('".$name."', '".$pass."')");
$result = mysqli_query($connection, "IF EXISTS(SELECT * FROM user WHERE name='".$name."'AND password='".$pass."')");
mysqli_close($connection);
echo "result ".$result;
if($result == True){
header("Location: logedin.php");
//redirect_to('logedin.php');
}else{
echo "not logged in installed";
}
?>
This is a late answer, but there are a few things you need to be made aware of. (Not taking away from the accepted answer).
You will need to use if(mysqli_num_rows($result) > 0) because your query will always be TRUE if the username matches and the password does NOT, and vice-versa.
You are better off using mysqli_num_rows() rather than using if($result == True)
Sidenote: Consult my footnotes regarding password storage and SQL injection.
<?php
$DB_HOST = "xxx";
$DB_NAME = "xxx";
$DB_PASS = "xxx";
$DB_USER = "xxx";
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
$name = $_POST["usname"]; // See footnotes about this
$pass = $_POST ["password"]; // See footnotes about this
$result = mysqli_query($db, "SELECT EXISTS(SELECT * FROM users WHERE username='".$name."' AND password='".$pass."')");
// Works just as well
// $result = mysqli_query($db, "SELECT * FROM users WHERE username='".$name."' AND password='".$pass."'");
if(mysqli_num_rows($result) > 0){
echo "Both match.";
}
else{
echo "Sorry, there was not a perfect match.";
}
Footnotes:
You can also use:
$result = mysqli_query($db, "SELECT * FROM users WHERE username='".$name."' AND password='".$pass."'");
Which does the same for SELECT EXISTS(SELECT * while using less characters.
or choose actual columns:
$result = mysqli_query($db, "SELECT username, password FROM users WHERE username='".$name."' AND password='".$pass."'");
I suggest that you use prepared statements and sanitize your inputs. Not doing so will leave you open to SQL injection.
Here are a few tutorials on (mysqli) prepared statements that you can study and try:
Tutorial one
Tutorial two
Tutorial three
Here are a few tutorials on PDO:
PDO tutorial one
PDO tutorial two
PDO tutorial three
Passwords
I also noticed that you are storing passwords in plain text. This is not recommended.
Use one of the following:
CRYPT_BLOWFISH
crypt()
bcrypt()
scrypt()
On OPENWALL
PBKDF2
PBKDF2 on PHP.net
PHP 5.5's password_hash() function.
Compatibility pack (if PHP < 5.5) https://github.com/ircmaxell/password_compat/
Other links:
PBKDF2 For PHP
I can't say anything about the PHP part, but the query will surely result in a syntax error.
IF whatever ... is only allowed in stored procedures or functions, not in single queries. You can however replace the IF with SELECT like
$result = mysqli_query($connection, "SELECT EXISTS(SELECT * FROM user WHERE name='".$name."'AND password='".$pass."')");
This query would return either 0 (if no entry exists) or 1 (if an entry exists). It's also a good idea to use EXISTS as it stops the query as soon as an entry was found and does not return the whole dataset.
You can try this beside using 'IF EXISTS' function--
$result = mysqli_query($connection, "SELECT * FROM user WHERE name='".$name."'AND password='".$pass."'");
$count=mysql_num_rows($result);
if($count==1) // $count=1 if any row is present with mathing username and pwd in db
{
echo "user already logged in";
}
else
{
echo "user not exist";
}
I've been modifying my code but I still can't log in... I have a MySQL database with a database called "users" with a table called "Users" and the following rows "UserNameID", "userName" and "password". I have created just an entry in order to test that:
+------------+----------+-----------+
| UserNameID | userName | password |
+------------+----------+-----------+
| 1 | root | pass |
+------------+----------+-----------+
Here my code:
<!DOCTYPE html>
<?php session_start(); ?>
<html>
<head>
<title>File1</title>
</head>
<body>
<?php
$DB_connection = mysqli_connect("localhost","user1","user1","users") or die("ERROR. Failed to connect to MySQL." . mysqli_error($DB_connection));
function SignIn() {
$usr = $_POST['user'];
$pw = $_POST['pwd'];
if(!empty($usr)) {
$query = mysql_query("SELECT * FROM Users where userName = '$usr' AND password = '$pw'");
$result = mysqli_query($DB_connection,$query);
if($result) {
while($row = mysqli_fetch_array($result)) {
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..."; }
} else {
echo "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY..."; } }
}
SignIn();
mysqli_close($DB_connection);
?>
</body>
</html>
When I introduce a wrong password or username, it gives me "SORRY... YOU ENTERD WRONG ID AND PASSWORD... PLEASE RETRY...". However, it throws me the same when I put the correct password and username. What is wrong in my code?
Thanks a lot!
There numerous issues here. There are scoping issues, you are using the wrong methods, it's unsafe.
First off, these 2 lines:
$query = mysql_query("SELECT * FROM Users where userName = '$usr' AND password = '$pw'");
$result = mysqli_query($DB_connection,$query);
That's not how you query a database. You only need to call either mysql_query or mysqli_query depending on what API you are using. You are using MySQLi in this case, so do this:
$query = "SELECT * FROM Users where userName = '$usr' AND password = '$pw'";
$result = mysqli_query($DB_connection,$query);
Second, your SignIn function can't access the $DB_connection variable, it's out of scope. You need to pass it in:
function SignIn($DB_connection){
}
SignIn($DB_connection);
Third, this code is very unsafe! Never use $_POST directly in an SQL query like that. You should never be concatenating variables into an SQL string, you should use prepared statements.
// Don't use "SELECT *", use the fields you want
$query = mysqli_prepare($DB_connection, 'SELECT user_id FROM Users where userName = ? AND password = ?');
// This sends the values separately, so SQL injection is a thing of the past
mysqli_stmt_bind_param($query, 'ss', $usr, $pw);
// Run the query
mysqli_stmt_execute($query);
// Prepared statements require to define exactly the fields you want
mysqli_stmt_bind_result($query, $user_id);
// Get the data
while(mysqli_stmt_fetch($query)){
echo $user_id;
}
mysqli_stmt_close($query);
Lastly, storing plaintext passwords is bad practice. Use a hashing library. PHP 5.5+ has one built-in (http://php.net/password). There's also a version for lesser PHP versions (https://github.com/ircmaxell/password_compat).
P.S. As pointed out in the comments (here's a link), your session_start() is in the wrong spot. That sends a header, so it requires that there be nothing echoed out before it.
<?php session_start(); ?>
<!DOCTYPE html>
<html>
Make sure that there is no whitespace (or anything) before the session_start().
Your problem is here:
$query = mysql_query("SELECT * FROM Users where userName = '$usr' AND password = '$pw'");
This should instead be
$query = "SELECT * FROM Users where userName = '$usr' AND password = '$pw'";
You're then passing the query string rather than a resource to mysqli_query.
(Also, refer to Shankar Damodaran's answer regarding the scope issue: pass $DB_connection to the SignIn function).
As a side note, you shouldn't use posted data directly into the query. You're at risk of SQL injection. Look into sanitizing the data or, preferably, prepared statements.
First of all, you are running into scope issues here.
In this line...
$result = mysqli_query($DB_connection,$query);
The variable $DB_connection is not accessible inside your SignIn() and thus your query is getting failed. Also you are mixing mysql_* (deprecated) functions with mysqli_* functions.
This simple and small code snippet for the login might help you..
$con = mysqli_connect("localhost","user1","user1","users") or die("ERROR. Failed to connect to MySQL." . mysqli_error($con));
$username = $_POST['username'];
$password = $_POST['userpassword'];
$result = mysqli_query($con,"SELECT * FROM users WHERE user_name = '$username' and user_password='$password'");
$count=mysqli_num_rows($result); // get total number of rows fetched. needs only 1 row for successful login.
if($count==1){
//Login successful
}
else{
//Login unsuccessful
}
It will fetch a row if the entered username and password are matched.It will fetch only one row as the username and password will be unique. If the count of rows fetched is '1' you can have successful login.