Welcome to our new updated tutorial, Android Login and Registration with PHP MySQL. In this tutorial we will create a simple App where user can register and then the user can login. So lets begin creating an app for Android Login and Registration with PHP MySQL.
1. Downloading & Installing WAMP
Download & Install WAMP server from www.wampserver.com/en/. Once installed, launch the program from Start ⇒ All Programs ⇒ WampServer ⇒ StartWampServer. If you are on Mac, alternatively you can use MAMP for the same.
You can test your server by opening the address http://localhost/ in your browser. Also you can check phpmyadmin by opening http://localhost/phpmyadmin
Following is a screencast of Downloading and Installing WAMP Server.
2. Creating MySQL Database and Tables
Open phpmyadmin and execute below queries to create necessary database and table. Here we are creating only one table users to store users login information.
create database android_login /** Creating Database **/
use android_login /** Selecting Database **/
create table users (
id int(11) primary key auto_increment,
unique_id varchar(250) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(250) not null,
created_at datetime
); /** Creating Users Table **/
3. Creating PHP Project
Goto the location where wamp installed and open www folder. The default installation location of wamp would be C:/wamp.
1. Go into www folder and create a folder named android_login. This will be the root directory of our project.
2. Now inside android_login, create a php file named config.php and add below content. Replace the $username and $password values with your’s.
<?php
$username = "root";
$password = "root";
$host = "localhost";
$dbname = "android_login";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try {
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
} catch(PDOException $ex) {
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
function undo_magic_quotes_gpc(&$array) {
foreach($array as &$value) {
if(is_array($value)) {
undo_magic_quotes_gpc($value);
}
else {
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
3.1 Registration Endpoint
Let’s start creating the endpoint for user registration. This endpoint accepts name, email and password as POST parameters and store the user in MySQL database.
3. In android_login root directory, create register.php and below code.
<?php
require("config.php");
if (!empty($_POST)) {
$response = array(
"error" => FALSE
);
$query = " SELECT 1 FROM users WHERE email = :email";
//now lets update what :user should be
$query_params = array(
':email' => $_POST['email']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["error"] = TRUE;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
$row = $stmt->fetch();
if ($row) {
$response["error"] = TRUE;
$response["message"] = "I'm sorry, this email is already in use";
die(json_encode($response));
} else {
$query = "INSERT INTO users ( unique_id, name, email, encrypted_password, created_at ) VALUES ( :uuid, :name, :email, :encrypted_password, NOW() ) ";
$query_params = array(
':uuid' => uniqid('', true),
':name' => $_POST['name'],
':email' => $_POST['email'],
':encrypted_password' => password_hash($_POST['password'], PASSWORD_DEFAULT) // encrypted password
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["error"] = TRUE;
$response["message"] = "Database Error2. Please Try Again!";
die(json_encode($response));
}
$response["error"] = FALSE;
$response["message"] = "Register successful!";
echo json_encode($response);
}
} else {
echo 'Android Learning';
}
?>
3.2 Login Endpoint
Just like registration, we need to create another endpoint for login. This endpoint accepts email and password as POST parameters. After receiving the email and password, it checks in database for matched user. If the user is matched, it echoes the success the json response.
4. Create a php file named login.php inside android_login with the below content.
<?php
require("config.php");
if (!empty($_POST)) {
$response = array("error" => FALSE);
$query = "SELECT * FROM users WHERE email = :email";
$query_params = array(
':email' => $_POST['email']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["error"] = true;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
$validated_info = false;
$login_ok = false;
$email = $_POST['email'];
$row = $stmt->fetch();
if (password_verify($_POST['password'], $row['encrypted_password'])) {
$login_ok = true;
}
if ($login_ok == true) {
$response["error"] = false;
$response["message"] = "Login successful!";
$response["user"]["name"] = $row["name"];
$response["user"]["email"] = $row["email"];
$response["user"]["uid"] = $row["unique_id"];
$response["user"]["created_at"] = $row["created_at"];
die(json_encode($response));
} else {
$response["error"] = true;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
} else {
echo 'Android Learning';
}
?>
3.3 Types of JSON Responses
The following are the different types of JSON responses for registration and login endpoints.
3.3.1 Registration
URL: http://localhost/android_login/register.php
PARAMS: name, email, password
Registration success response
{
"error": false,
"message": "Register successful!"
}
Registration error in storing
{
"error": true,
"message": "Database Error1. Please Try Again!"
}
Registration error – User Already Existed
{
"error": true,
"message": "I’m sorry, this email is already in use"
}
3.3.2 Login
URL: http://localhost/android_login/login.php
PARAMS: email, password
Login Success
{
"error": false,
"message": "Login successful!",
"user": {
"name": "Akshay Raj",
"email": "[email protected]",
"created_at": "2016-06-16 08:43:48"
}
}
Login error – Incorrect username / password
{
"error": true,
"message": "Invalid Credentials!"
}
Now we have completed the PHP part. Let’s start the android part.
Thank you!
Very good! good explanation!
welcome 🙂
please help me, i have problem my project from your code.
this my problem :
08-29 11:30:30.867 19451-19451/com.dani.skripsi.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dani.skripsi.myapplication, PID: 19451
java.lang.NullPointerException: Attempt to invoke virtual method ‘void com.dani.skripsi.myapplication.MyApplication.addToRequestQueue(com.android.volley.Request, java.lang.String)’ on a null object reference
at com.dani.skripsi.myapplication.RegisterActivity.registerUser(RegisterActivity.java:141)
at com.dani.skripsi.myapplication.RegisterActivity.access$300(RegisterActivity.java:24)
at com.dani.skripsi.myapplication.RegisterActivity$1.onClick(RegisterActivity.java:57)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19761)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5264)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:900)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:695)
com.dani.skripsi.myapplication.RegisterActivity.registerUser(RegisterActivity.java:141)
click on bold text in your error RegisterActivity.java:141 and send your code line
hi thanks for sharing . i run this project in real server but i got some errors and i know that errors happened for addresses . so here we go :
this my login and register path :
private static final String URL_LOGIN = “http://memaraneha.ir/Erfan/android_login/login.php”;
private static final String URL_LOGIN = “http://memaraneha.ir/Erfan/android_login/register.php”;
and this is my config info (i am sure about correct and existing These) :
$username = “yashilgo_eri”;
$password = “erfan1373”;
$host = “memaraneha.ir”;
$dbname = “yashilgo_erfan”;
so what is wrong ?
Change URL_LOGIN to URL_REGISTER in 2nd line. Also check url in login and registration method
nothing is getting entered in wamp server database and whn iregister a black circle comes at the bottom
E/Volley: [6156] BasicNetwork.performRequest: Unexpected response code 403 for http://192.168.1.3/android_login/login.php
E/LoginActivity: Login Error: null
E/ViewRootImpl: sendUserActionEvent() mView == null
Open your url in browser and check error
it shows Android Learning
Check in mobile browser
U dont have permission to access /adroid_login/login.php on this server
Apache/2.4.18(Win64)PHP/5.6.19 Server at 192.168.1.3 Port 80
This is the message
Check your wamp server is online.
http://cdn.windows7themes.net/pics/wampserver-start-all-services-put-online.jpg
yes it is online i restarted all services and also did as per ur image
Check your wamp server settings and ip address.
Ip address is correct andwhatwamp settings should i do??
where is the PHP code to validate the password ??? I can Login using any password 😀
Sorry.. It’s my mistake. I updated my code. Thank you for showing my mistake.
where is the password checking code in php file of login ??? …… it is working with wrong password also
ohh i found your password code but code is not working after adding password related code please check 🙂
oh it was my mistake …thanks it is working and nice tutorial i tried one more tutorial which was not working for me bcoz of result_get() method which is use in sqlnd but this tuto is working 🙂
Thank you raman 🙂
How would you scale the backend and add frontend views for user groups (a user can be part of multiple groups (checkboxes ? maybe)
and user profiles (search and view)
and add Push notification layer when a new user joins for other to see his profile and contact him if needed
registration works but when I try to login it says Json error: Value <br of type java.lang.String can not be converted to JSONObject
i updated my code.
akshay ji aapko codeing main kuch prb hai when i creat that code the application was unfortunatly has stoped error is show
ok… i’ll check and update my code.
i updated my code.
Can you tell me where have you made a change because I can’t find update that you made so please point out where should i need some changes ASAP.
line 32 in login.php
if (password_verify($_POST['password'], $row['encrypted_password'])) {
Thank you for your instant replay much appreciated man. Keep doing what you are doing. Thanks again
please hope this works fine
hello akshay bro can i got your contact no. plz my contact no. is 9229788000
Hello thank but I have a problem.
Im using azure to my host and my dtaba base, when I put android_login_api/register.php or android_login_api/login.php I have the message that say error_msg: “Required parameters email or password is missing!” so I put like android_login_api/[email protected] but it doesn´t work.
Please helpe!!! what can I do?
Thanks
your database not receiving any values.
Thank you but I have a problème:
java.net.ConnectException:failed to
connect to /192.168.1.100(port 80)after
5000ms:isConnected failed:
EHOSTUNREACH (No route to host)
Please helpe me !! what can I do?
Thanks.
change url with your localhost server ip address.
Thanks, but I have another probléme.
He wrote me blank message.
Thanks
send me screenshot of error to my facebook (https://www.facebook.com/akrajilwar)
bro i need java and php code for login and registration with database and validation
go to this link Android Login Registration System with PHP, MySQL and Sqlite
ibra first check u r systems ip address than that ip address place on u r app
hi akhsay im also gettin a null pointer on
MyApplication.getInstance().addToRequestQueue(strReq, tag_string_req);
im compilin on sdk 25.
i also notice on volley im gettin error on AndroidHttpClient.
is this due to its depreciation?
ty in adv
add MyApplication to your manifest:
It works very nice ,but how to prevent showing login page when user open the app next time..It is show login page every time I open the app.
i’m posting a new tutorial very soon about store login data in session, reset password and verify email.
I tried your code. it throws error in import ‘android.support.design.widget.TextInputLayout’. please help me to fix it.
Use Design Support Library with this Gradle dependencies:-
compile 'com.android.support:design:25.3.0'
Hai, am a beginner and i don’t know what i wanna do with the “JSON Responses”????
1: if i want to store it some file like .php or wot?
please get me out with this!
Hi, AKSHAY RAJ do you have PHP coding for update password?
Yes, check out this post Android Login Registration System with PHP, MySQL and Sqlite
Sir I am a begineer and i want to understand how will be I able to integrate my android code with my php or server programming on same IDE platform using localhhost. Can u explain in brief.
check full source code Android-Login-And-Registration
Bonjour,
Super boulot, probleme après essaie enregistrement rien ne se passe. J’ai enregistring qui s’affiche avec le screen qui tourne mais pas d’enregistrement dans base de donnée.
Merci de votre aide
please i am getting unresolved method getEditText
Same!
Send your query to our facebook page or whatsapp support.
Impressive and very well explained
Hello
I get a blank message after i click on register. Can you help me please
can you show me android log when you click register button? You can contact me on facebook or Whatsapp.
thanks, for this tuto i use xampp server so i should set these files in htdocs forlder.
yes.
Very good explanation.
I copied all files to my project, but I’m unable to assign MyApplication as the startscreen. It refuses in the manifest.
What am I doing wrong?
All compiled with success.
Hello Marc, check error on Log Monitor
Wrong place 🙂
Ok ?