Hello guys I'm doing an simple login system in android to mysql database online. This is what I've tried so far:
MainActivity:
protected String doInBackground(String... args) {
strUsername = etUsername.getText().toString();
strPassword = etPassword.getText().toString();
try{
String data = URLEncoder.encode("username", "UTF-8")
+ " = " + URLEncoder.encode(strUsername, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ " = " + URLEncoder.encode(strPassword, "UTF-8");
URL url = new URL(url_login);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
Log.e("TAG", sb.toString());
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
PHP side:
<?php
// Connect to dbconnect.php
include('dbconnect.php');
// array for JSON response
$response = array();
// username and password sent from form
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn->prepare('SELECT username, password FROM customer WHERE username = :username AND password = :password');
$stmt->execute(array(':username' => $username, ':password' => $password ));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$user = $result['username'];
$affected_rows = $stmt->rowCount();
if($affected_rows >= 1){
$response["success"] = 1;
// successfully inserted into database
$response["message"] = "New record successfully created.";
// echoing JSON response
echo json_encode($response);
}
else{
$response["success"] = 0;
echo json_encode($response);
}
?>
Sample record:
Username: admin Password: admin
I tried to run this but it's getting a response: success: 0 which means not successful. What am I doing wrong in here? I would gladly appreciate your help. Thanks a lot.