Accessing mySQL on WAMP from Android - java

I am having trouble understanding how exactly to configure WAMP for remote (not LAN) access by an Android app to the SQL database that I have created with it.
I understand that I shouldn't be directly connecting to the database from the app but use a PHP script to query the database and return the results.
What I am not understanding is how all this fits together, Where do I put the PHP scripts, How do I access them, How do I allow and connect to the webserver to get the data out of the database.
I have followed and searched for lots of tutorials on this but they all seem to deal with only using wamp in localhost, I can successfully access the data locally but I am stumped with how to set all that up so that I could query the database from any internet connection on my android device.
Any advice on how to achieve this would be very much appreciated.

You have to upload your php script to your server :
Ex : Your php is in : myserver.com/myscript.php
In your Android app, You post your variables, and you connect your php script with HttpClient :
URL_TO_YOUR_SCRIPT = "myserver.com/myscript.php";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userId", userId));
HttpClient httpclient = new DefaultHttpClient();
// specify the URL you want to post to
HttpPost httppost = new HttpPost(URL_TO_YOUR_SCRIPT);
try {
// create a list to store HTTP variables and their values
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
HttpEntity getResponseEntity = response.getEntity();
return getResponseEntity.getContent();
} else {
Log.e("ERROR", statusLine.getStatusCode() + "");
HttpEntity getResponseEntity = response.getEntity();
return getResponseEntity.getContent();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
In your php :
<?
$userId=$_REQUEST['userId'];
....
// in general you return a json string to get status and result
?>

Related

How to connect Android app with MySQL database through PHP

I am still a little skeptical as to how to connect my Android app to a PHP script. I saw somewhere that the following code will connect the app to the server. But I am new at android so I do not know how to really use it.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://url.to.my.app.com");
HttpResponse response = httpClient.execute(httpGet);
// handle response'
I understand that this opens a connection to an online server, but what I do not understand is what kind of response is returned by the server and how to process it. Also, I want to know how to send data through POST to the server from my app.
(If you could provide some code of your own, that would be helpful too) Thanks!
This will open a connection and send a http GET request to server. Your PHP script executes on the server side for this request and returns some contents. You can use folowing code to process the response.
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
}
For POST execution you need to do something like this.
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("test1","test1" ));
nvps.add(new BasicNameValuePair("test2", "test2" ));
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}

Application getting website response

net developer and dont know about android. could you please help me to fix this code
Exception: android.os.networkmainthreadException on
client.execute(get1)
try
{
HttpGet get1 = new HttpGet ("http://www.google.com/");
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get1);
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
}
catch(Exception e )
{
urlview.setText( "hi bug"+ e.toString());
}
You are doing network operation on UI thread which in not allowed in android version >=3.0 So use AsyncTask

mysql insert with java and php: no error but no insert

I have an Android java method that calls a remote php to insert data into a mysql table.
This is java code client side:
public static void insert(String email1, String email2) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email1", email1));
nameValuePairs.add(new BasicNameValuePair("email2", email2));
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myserver:8080/insert.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//How to catch and print php echo() here??
}
and this is the insert.php server side (re-edited):
<?php
$mysqli_connection = new mysqli("localhost:3306", "root", "password", "mydb");
if ($mysqli_connection->connect_errno) {
echo ("Connection Failure");
exit();
}
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("INSERT INTO `mytable` (`email1`, `email2`) VALUES (?,?)")) {
echo 'Success';
$stmt->bind_param("ss", $_GET['email1'], $_GET['email2']);
$stmt->execute();
$stmt->close();
} else {
echo 'Error Inserting Content';
}
$mysqli->close();
?>
When I call my java insert() method, no exception is returned, but no insert is done and mytable is empty.
1) What is wrong?
2) How can I see which error occured? How can I see a "log" of the the php-side execution?
Thank you very much.
Geltry
use backtick instead of single quote for column names and/or tableNames
INSERT INTO mytable(`email1`,`email2`) VALUES('$email1','$email2')
when do you use backtick?
when column name or table name is a Reserved Keyword in MySQL
when it contains space,
eg,
CREATE TABLE `hello word`(`Record ID` INT,....)
and you query is vulnerable with SQL Injection, please take time to read the article below
How can I prevent SQL injection in PHP?
Look into your HttpResponse/HttpEntity. There you should see either 'Success' or 'Error Inserting Content'. You can also add the concrete errno and error string in your response to see, what's really going wrong.
You also mix HTTP POST and HTTP GET in your request. On the client side you use a HttpPost object and on the server side you expect the _GET variables to be set. You must use either GET or POST on both sides. Otherwise client and server won't understand each other.
With HttpEntity.getContent() you can read from an InputStream. Another approach would be to use EntityUtils.toString() to get a string representation of the response's content.

Android http post advanced request with body on hostmachine

I would like to do a HTTP post request from my virtual android device on the hostmachine.
Below you'll see an image on how I post, by using the old WebFetch tool.
I don't know what URL to use for calling the hostmachine?
I got no idea how my body string can be used an input?
Does anybody have an idea on how to solve this?
If you want to connect to the computer which is running the Android simulator, use the IP address 10.0.2.2. You can read more about it here.
Also check out the accepted answer in following question to see how json can be send as post data:
How to send POST request in JSON using HTTPClient?
you can use following code to make HTTP get request:
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://10.0.2.2:port/your_path_with_parameter";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
} catch (Exception e) {
e.printStackTrace();
}

Trouble POSTING from Android/Java app to PHP + MYSQL

I have been trying to get my Android App to post data to a PHP file, which then writes that data to a database, however I'm having a bit of trouble with it.
I'm getting this error, however it's not force closing or anything.
Logcat Output:
08-13 20:29:42.859: I/postData(11950): HTTP/1.1 200 OK
08-13 20:29:42.859: E/log_tag(11950): Error in http connectionjava.lang.IllegalStateException: Content has been consumed
Here is the code in question that's doing all my HTTP POST stuff, the android side of things:
SubmitWord task = new SubmitWord();
task.execute(new String[] { "http://www.hanged.comli.com/main.php" });
The above code calls this asynchronous task:
private class SubmitWord extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls)
{
String response = "";
try
{
URL = urls[0];
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("victim",myId));
nameValuePairs.add(new BasicNameValuePair("rival",newname));
nameValuePairs.add(new BasicNameValuePair("word","HELLOHOMO"));
nameValuePairs.add(new BasicNameValuePair("won","0"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse execute = httpclient.execute(httppost);
HttpEntity entity = execute.getEntity();
InputStream is = entity.getContent();
Log.i("postData", execute.getStatusLine().toString());
//HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}
return response;
}
#Override
protected void onPostExecute(String result)
{
mText.setText("DONE");
}
}
Here is the PHP side of things:
<?php
/// REMOVED DATABASE DETAILS
$connect = mysql_connect("$mysql_host", "$mysql_user", "$mysql_password")or die("cannot connect");
mysql_select_db("$mysql_database", $connect)or die("cannot select DB");
session_start();
$victim = $_POST['victim'];
$rival = $_POST['rival'];
$word = $_POST['word'];
$won = $_POST['won'];
mysql_query("INSERT INTO currentgames (victim, rival, wordguess, won) VALUES('$victim', '$rival', '$word', '$won'))");
I'm fairly sure it's just the Java/Android part that I've gotten wrong, but I can't figure out for the life of me what I'm doing wrong, I have tried various different methods of POSTING data and read a number of tutorials on using HTTPOST. Maybe I'm just not understanding correctly.
The culprit is you are calling getContent(); twice.
As per javadoc
Returns a content stream of the entity. Repeatable entities are expected to create a new instance of InputStream for each invocation of this method and therefore can be consumed multiple times. Entities that are not repeatable are expected to return the same InputStream instance and therefore may not be consumed more than once.

Categories