I havnt been able to find a guide on how to submit data to a database from android through php.
say for instance i have the following site:
function insert($var1) {
// mysql inserting a new row
$result = mysql_query("INSERT INTO report (name) VALUES ('$var1')");
// check if row inserted or not
if ($result) {
// successfully inserted into database;
$msg = "Message received.";
} else {
$msg = "Not received.";
}
return ($msg);
}
if (isset($_POST['name'])) {
$name = $_POST['name']);
insert($name);
} else {
echo "No input.";
}
How would i call this from my Android project?
You can refer to this tutorial but you do need a web-server for it.
Request mechanism Android App ----> webserver ------> database (mysql)
Respond mechanism Android App <---- webserver <------ database (mysql)
Android App will use JSON or other to get the data and display it
PHP Code
<?php
$con=mysql_connect("host","username");
if(!$con)
{
die("Could Not Connect".mysql_error());
}
$db="CREATE DATABASE login";
mysql_query($db,$con);
mysql_select_db("login",$con);
$tab="CREATE TABLE info(FirstName varchar(20),LastName varchar(20))";
mysql_query($tab,$con);
$user_fname=$_POST['fn'];
$user_lname=$_POST['ln'];
$row= mysql_query("INSERT INTO info (FirstName,LastName) VALUES('$user_fname', '$user_lname')");
if ($row) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
echo $row;
}
mysql_close($con);
?>
Sending the Data (Android)
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1:4001/file.php");
List<NameValuePair> pair=new ArrayList<NameValuePair>(2);
pair.add(new BasicNameValuePair("fn",fname));
pair.add(new BasicNameValuePair("ln",lname));
httppost.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse response = httpclient.execute(httppost);
Related
I am trying to get a single field from MySQL through php and use it in my android app.. how can i get a single field when reading response from php to android without using json?
or if there is any tutorial that can help me , I'll be grateful
here's my Code
public Boolean postData(String a,String b) {
response = null;
String response = null;
try
{
// url = new URL("http://"+"URL"+"/new/check2.php");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("check",x));
postParameters.add(new BasicNameValuePair("username", a));
postParameters.add(new BasicNameValuePair("password", b));
response = CustomHttpClient.executeHttpPost("http://"+"URL"+"/new/checkedited.php",postParameters);
// result = response.toString();
result = result.replaceAll("\\s+", "");
}
catch(Exception e)
{
e.printStackTrace();
}
return true;
}
PHP
<?php
$host=""; // Host name
$user=""; // Mysql username
$pswd=""; // Mysql password
$db="pet_home"; // Database name
//$tbl_name="users"; // Table name
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
$username=$_POST['username'];
$password=$_POST['password'];
$result=mysql_query("select * from users where username='$username' and
password='$password'")or die (mysql_error());
$count=mysql_num_rows($result);
$row=mysql_fetch_array($result);
if ($count > 0){
echo "\n";
echo $row['filter_st'];
echo "\n";
echo $row['heat_st'];
echo "\n";
echo $row['led_st'];
}else{
echo 0;
}
?>
Just echo the single field then, no parsers, no JSON no nothing...
for example if you want 'heat_st': (just one echo, since the echo is the response you phone gets)
echo $row['heat_st'];
Then the response to your android app will be just that one String which is the result you wanted.( you can easily convert it to int for example in Java if you need to )
if you need multiple fields, JSON is the way to go.
I am new to android development. As part of a bigger project I want to insert data from an android device to a web-server. So I did some research and articles like The article from androidhive and this article from codeproject were really helpful in trying to develop a test-app which inserts in to a mysql db, which is residing at a remote web-server.
Here is my android code
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxxxxx.in/installment.php");
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", editTextCustomer.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("amount", editTextAmount.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
Log.i("postData", response.getStatusLine().toString());
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
}
else {
Toast.makeText(PayBillActivity.this, "Internet Access, Denied!!", Toast.LENGTH_LONG).show();
}
Here is the php code
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['amount'])) {
$name = $_POST['name'];
$amount = $_POST['amount'];
$con=mysqli_connect("localhost","db_user","passwd","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO installment (name, amount) VALUES ('$_POST[name]','$_POST[amount]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
// check if row inserted or not
if ($sql) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Installment made successfully";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
echo $result;
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
//$amount = 1000;
//echo $amount;
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
when I run the app, I am getting this "NetworkOnMainThreadException" exception and as a result no rows are being added. But its working perfect with HTML POST.
Can anyone tell me where the problem is in my code?
Thanks in advance!:)
I think if you spent the time you did on posting this question into google you may have got some good answers... Just to complete this question
There are two options available with you, either you can add a line of code and allow network operation on main thread, but its very very bad for your app and also as a coding style.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
The longer option is to redesign the code to have the network operations performed in a separate thread. This is both good for the app and you will learn how to work on a multi-threaded program.
I think you should not use that strict or take it manually out of main..
Just use a smart premade lib and it is making all for you !
Download : http://loopj.com/android-async-http/
Note: And this lib is even using gzip to compress requests :)
I am a beginner in Android and I have the following code:
(On the PHP side, after the user logs into my Android App)
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$query = mysql_query("SELECT * FROM users WHERE c_name='$username' AND c_password='$password'") or die("Could not run query!");
$rows = mysql_num_rows($query);
if($rows == 0){
echo "No user was found";
}else{
$row = mysql_fetch_assoc($query);
$_SESSION['id'] = $row['id'];
$_SESSION['username'] = $row['c_name'];
echo "User Found";
}
In the file where I want to obtain the ID of the user whom was logged in I have:
session_start();
$r_name = $_POST['r_name'];
$r_address = $_POST['r_address'];
$r_phone = $_POST['r_phone'];
$r_username = $_POST['r_username'];
$req_id = $_SESSION['id'];
$req_username = $_SESSION['username'];
$query_add = "INSERT INTO data_collection VALUES ('','$r_name','$r_address','$r_phone','$r_username','$req_id')";
$query_exec = mysql_query($query_add) or die("Could not insert to db");
if($query_exec){
echo "Success";
}else
echo "Error in query";
And the Android side that posts the data to the 2nd php file:
public void onClick(View v) {
// TODO Auto-generated method stub
String s_res_name = res_name.getText().toString();
String s_res_address = res_address.getText().toString();
String s_res_phone = res_phone.getText().toString();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("r_name", s_res_name));//c_name is the value in PHP and in the mySQL db
nameValuePairs.add(new BasicNameValuePair("r_address", s_res_address));
nameValuePairs.add(new BasicNameValuePair("r_phone", s_res_phone));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/thesis/data_collection.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,responseHandler);
tv.setText(""+response);
if (response.equals("Success")){
Toast toast = Toast.makeText(getApplicationContext(), "Data Collection task successfully created", Toast.LENGTH_LONG);
toast.show();
finish();
}
}catch(Exception e){
Log.e("log.tag","Error in http connection"+e.toString());
}
}
});
How can I obtain the session ID in the second php file and store it in a new table?
This code runs well through the web, when I post the data through a form, but on the android side it doesn't...
Thank you for your help.
How can I obtain the session ID in the second php file and store it in a new table?
The session ID is part of the request. If you mean $_SESSION['id'] you need to call session_start() first or have session auto-start configured.
Do I have to do sth on the Android side? Thank you for your help.
Yes, you need to pass the real session ID (not that $_SESSION['id'] value), it's a cookie or a query-parameter commonly named PHPSESSID by default. See also session-name. If you don't pass that info with the request, PHP does not know which session this request should belong to.
For more info, please continue here: http://php.net/sessions
In my applications I do it this way:
I have PHP script, that do real login. This script return string as "HTML page". That page is erad within application, string is parsed and data from that string are used in application for login.
Example of return string:
nick|user_id|hashed_security_string
Now in nick you have user name, user_id is his ID from DB and hashed_security_string is something used for security purposes when you for example commit something from your app to DB, this string is send with data and controlled on server if user is really logged or if user exist.
I have created a webservice called "login.php" where I send the id and password information from android. The webservice successfully catches the id and password. I need to compare that id and password to the ones already present in the database and check whether they exist or not. If they do, I need to send back an "okay message" back to android so I can start a new intent. If the id and password do not exist, I want to display an error.
Below is my code.
Login.java
HttpPost httppost = new HttpPost("http://abc.com/webservice/Login.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", et1.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("pass", et2.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
client.execute(httppost);
Log.d("valueeeeeeeeeeee", et6.getText().toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.d("exppppppp", "msg");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("exppppppp", "msg");
}
Login.php:
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": ".mysql_error()."<BR>");
$userid = $_POST['userid'];
$pass = $_POST['pass'];
$db_select=mysql_select_db("my_db");
if(!$db_select){
die(mysql_error());
echo "error";
}
What query should I run here to check the database against the specific id and password it recieved and send back an "okay message" to the android app. Thanks
You can try something like this:
Java:
HttpPost httppost = new HttpPost("http://abc.com/webservice/Login.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userid", et1.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("pass", et2.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//This piece of code should do the trick
HttpResponse response = client.execute(httppost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
// EntityUtils to get the reponse content
String content = EntityUtils.toString(respEntity);
}
Log.d("valueeeeeeeeeeee", et6.getText().toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.d("exppppppp", "msg");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("exppppppp", "msg");
}
PHP:
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": ".mysql_error()."<BR>");
$userid = mysql_real_escape_string($_POST['userid']);
$pass = mysql_real_escape_string($_POST['pass']);
$db_select=mysql_select_db("my_db");
if(!$db_select){
die(mysql_error());
echo "error";
}
$query = "select count(1) as count_users from user_table where user_field = '".$userid."' and pass_field ='".$pass."'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if($row['count_users']>0)
{
echo "Okey";
}
else
{
echo "Not found";
}
?>
PS: Please dont use the mysql_extension, go for mysqli or PDO instead.
I would recommend doing as you are. Initiate a HTTP post/get request to a PHP page which connects to the MySQL database using mysqli (mysql_query is deprecated). You can then form the result into a JSON response to be passed back and can be easily parsed in android to extract any wanted information. I would recommend these tutorials:
Connect android with PHP and MySql, JSON in android and PHP and MySQLi
I used these tutorials and managed to get what you are trying to do working without too much difficulty.
You can access the passed get variables sent from android using
$_GET['userid'] and $_GET['pass']
and a valid SQL query would be
$query = 'SELECT * FROM '%table_name%' WHERE uname ="'.$_GET['uname'].'" AND pass ="'.$_GET['pass'].'"';
You need to beware though as using unchecked input directly in SQL statements leaves you susceptible to SQL injection attacks and should be avoided if at all possible. For the purposes of investigating and experimenting on a private server you should be okay though. Be aware that that there is are a lot of security issues to consider before distributing software with server connectivity
I could really need some help to my project.
I have an android app, that scans for wireless networks. I want to upload this data to a mysql database.
Android have database class:
public class Database {
public static void putServerData(String building, String floor, String room, String address, String signal){
String db_url = "http://**(IP ADDRESS)**/setdata.php";
#SuppressWarnings("unused")
InputStream is = null;
ArrayList<NameValuePair> request = new ArrayList<NameValuePair>();
request.add(new BasicNameValuePair("building",building));
request.add(new BasicNameValuePair("floor",floor));
request.add(new BasicNameValuePair("room",room));
request.add(new BasicNameValuePair("address",address));
request.add(new BasicNameValuePair("signal",signal));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(db_url);
httppost.setEntity(new UrlEncodedFormEntity(request));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
}
}
This is called by:
try {
Database.putServerData(building,floor, room, array1.get(1).toString(), array2.get(2).toString());
} catch (Exception e) {
Log.e("test", "test");
}
The server is a Win7 machine, with apache php and mysql
The setdata.php file:
<?php
$con = mysql_connect("localhost","root","pass");
if(!$con)
{
echo 'Not connected';
echo ' - ';
}else
{
echo 'Connection Established';
echo ' - ';
}
$db = mysql_select_db("android");
if(!$db)
{
echo 'No database selected';
}else
{
echo 'Database selected';
}
$building = $_POST['building'];
$floor = $_POST['floor'];
$room = $_POST['room'];
$ap_mac1 = $_POST['ap_mac1'];
$ap_strength1 = $_POST['ap_strength1'];
$ap_mac2 = $_POST['ap_mac2'];
$ap_strength2 = $_POST['ap_strength2'];
$ap_mac3 = $_POST['ap_mac3'];
$ap_strength3 = $_POST['ap_strength3'];
$ap_mac4 = $_POST['ap_mac4'];
$ap_strength4 = $_POST['ap_strength4'];
$ap_mac5 = $_POST['ap_mac5'];
$ap_strength5 = $_POST['ap_strength5'];
echo ($_POST['building']);
mysql_query("INSERT INTO wifiscan VALUES($nextid, '$building','$floor','$room','$ap_mac1','$ap_strength1','$ap_mac2','$ap_strength2', '$ap_mac3', '$ap_strength3', '$ap_mac4', '$ap_strength4', '$ap_mac5', '$ap_strength5')");
mysql_close(); ?>
This is not working. Im not sure i select the database in the correct way, could that be the problem?
Maybe this isnt so clear and ill will explain it further if you want.
Use some Log and maybe sprintfs to figure out what is exactly going on.
I#d start with the PHP. Try to open the URL from your browser and put some outputs in the PHP to see if everything works fine here. Post your results and you will probably get further help.