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.
Related
I have been searching everywhere this question and the only answer i've seen is JSON! I feel there is also other ways to do this.
My problem is i can post data from android to php script to insert data to my server. But what i want to do is get some data from my php to android. (without using JSON).
Please, i'm still in the basics. Make this as simple as possible!
Here's my php script:
<?php
$con=mysqli_connect("HOST", "USER", "PASSWORD", "DB_NAME");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$tablenamep = $_POST["tablenamep"];
$stringp = $_POST["stringp"];
$val = mysqli_query($con, "DESCRIBE `$tablenamep`");
if($val == TRUE) {
echo "Table exists";
$stringp = "This ID already exists. Try again!";
} else {
echo "Table does not exist";
mysqli_query($con, "CREATE TABLE ".$tablenamep." ( name VARCHAR(30), number INT, email VARCHAR(30))");
$stringp = "Your ID is available";
}
mysqli_close($con);
?>
This is how i used my java class to post data to php script.
public void CONNECT_SERVER(){
String msg = etID.getText().toString();
if (msg.length()>0){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myfile.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("tablenamep", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
} else {
Toast.makeText(getBaseContext(),"All field are required",Toast.LENGTH_SHORT).show(); }
}
The php script and android app is working FINE, no errors! Now i can add the data from my android app to the php script. NO PROBLEMS TILL NOW!
BUT WHAT I WANT, is to get the $stringp variable from the php script above to my android app after executing the script. In other words i want my app to know whether the ID exists or not.
I have already checked many forums regarding this question. SOLVE THIS PROBLEM WITHOUT JSON.
You must use json or other parsing method to retrieve data from server
try this
contact.php
<?php
mysql_connect ("localhost","root","");
mysql_select_db("meetapp");
$output=array();
$q=mysql_query("SELECT `app_id` FROM `registration`");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print (json_encode($output));
mysql_close();
?>
in your java code
try {
HttpClient httpclient2 = new DefaultHttpClient();
HttpPost httppost2 = new HttpPost("http://10.0.2.2:80/contact.php");
HttpResponse response2 = httpclient2.execute(httppost2);
HttpEntity entity2 = response2.getEntity();
is2 = entity2.getContent();
Log.e("log_tag", "connection success ");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
try
{
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb2 = new StringBuilder();
String line = null;
while ((line = reader2.readLine()) != null)
{
sb2.append(line + "\n");
}
is.close();
result3=sb2.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
try
{
JSONArray jArray2 = new JSONArray(result3);
String s11;
Log.w("Lengh",""+jArray2.length());
for(int i=0;i<jArray2.length();i++){
JSONObject json_data2 = jArray2.getJSONObject(i);
s11=json_data2.getString("app_id");
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
Hi,
i use this class to make a request to server, which consist of the json data object.
Class is:-
public class HttpClient {
private static String URL = "localhost/json/json_handle.php";
public String postJsonData(String data) {
try {
StringBuffer buffer = new StringBuffer();
// Apache HTTP Reqeust
System.out.println("Sending data..");
System.out.println("Data: [" + data + "]");
org.apache.http.client.HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
List<NameValuePair> nvList = new ArrayList<NameValuePair>();
BasicNameValuePair bnvp = new BasicNameValuePair("json", data.toString());
// We can add more
nvList.add(bnvp);
post.setEntity(new UrlEncodedFormEntity(nvList));
HttpResponse resp = client.execute(post);
// We read the response
InputStream is = resp.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
is.close();
buffer.append(str.toString());
// Done!
return buffer.toString();
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
}
Then i use a php class on server side to get the json object from the request. But, at server side i am getting nothing. Even when i use $_REQUEST method, then code after this method doesn't work.
Here is my php file:-
<?php
$file = fopen("MyFile.txt" ,"w");
$int = $_REQUEST;
fwrite($file,"aaa");
//$input =$_REQUEST['json'];
fwrite($file,"HELLO 111");
//$data = json_decode($input,true);
/*print_r($input);
// get values
$firstname = $input->firstName;
$surename = $input->lastName;
$age = intval($input->age);
// check values
if (isset($firstname) && !empty($firstname) &&
isset($surename) && !empty($surename) &&
isset($age) && is_numeric($age))
{
// do something
echo "Hello ".htmlspecialchars($firstname)." ".htmlspecialchars($surename)."!<br>";
echo "You are $age years old! Wow.";
}
else
{
echo "Some values are missing or incorrect";
}*/
//fwrite($file, $data);
fclose($file);
?>
Any suggestions regarding this problem???
Thanks friends for your help.
I got the solution and now the program is working perfectly on localhost as well as online.
For localhost, we just have to give the URL as:-
1.1.1.1/json/json_handle.php
where 1.1.1.1 is your ip address.
Again, thanks alot friends.
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 from php to android without using json? im trying to set a radiobutton's text into the field i get? here's my php code:
<?php
$con = mysql_connect("localhost","root","pass123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("voting", $con);
$result = mysql_query("SELECT Name FROM ssc_president WHERE Party = '123'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
$pname = $row['Name'];
//echo "Name: ".$row['Name'];
mysql_close($con);
?>
You can use XML to get single name from server other than that You will have to hard code text of radio button in android.
To get dynamic data from server you need to call webservice which give data either in XML or JSON. Its depend on which you are using.
From PHP, simply echo the field you want. Make sure that is all you print.
<?php
...
echo $mydata;
?>
And from Android, read it with an HttpClient
String result = "";
InputStream is=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("MyURLGoesHERE");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
String line = "";
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
}catch(Exception ex){
Log.e("Error",ex.toString());
}
Log.d("DataFromPHP",result);
I have a problem connecting database with Android app. I am trying to implement this tutorial. Everything seems to be fine but I neither get any success not an error.
There is a button listener which on clicking does a post to a PHP file and gets the result. Here is the code for it:-
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/check.php", postParameters);
String res=response.toString();
Log.d("res:", res);
// res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
if(res.equals("1"))
error.setText("Correct Username or Password");
else
error.setText("Sorry!! Incorrect Username or Password");
} catch (Exception e) {
un.setText(e.toString());
}
}
});
Here is the http post method:-
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
Log.d("postMethodReturn", result);
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The PHP code is as below:-
<?php
$un=$_POST['username'];
$pw=$_POST['password'];
//connect to the db
$user = "xyz";
$pswd = "xyz";
$db = "mydb";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);
//run the query to search for the username and password the match
$query = "SELECT * FROM mytable WHERE user = '$un' AND pass = '$pw'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) --> 0)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
Is there any bug in the program? I tried logging the intermediate values of res (http response) in activity code and result in the execute post method, but nothing is being logged. Tried changing "localhost" to "127.0.0.1" and also into a publicly available webhost, with all the database environment, but no success. All these on emulator and with public host, tried with real device too. Server seems to be running when checked from browser. Database exists with the values. All services running (apache, mysql).
The main problem is that there is no error! Any suggestions what is going wrong?
Couldn't find anyone with the same problem.
the problem was --> in the PHP code. changed it to == or > and everything works fine!
I have an android app that sends a json string to my server and it is formatted as follows:
{"drink_name":"testing","phone_number":"5555555555"}
When I use the command: SELECT * FROM orders, it shows that blank entries were inserted into the table.
I think my issue is arising from my PHP script (mainly because I am new to PHP).
Am I parsing the json correctly?
Below is the script that I wrote.
<?php
$handle = mysql_connect('localhost',USERNAME,PASSWORD);
if($handle==false)
{
die('No database connection');
}
$db=mysql_select_db('r2bar2');
$json = file_get_contents('php://input');
$obj = json_decode($json);
mysql_query("INSERT INTO orders (phone_number, drink_name)
VALUES ('".$obj->{'phone_number'}."', '".$obj->{'drink_name'}."')");
mysql_close($handle);
?>
EDIT:
Here is my Android code if it is any help.
protected void sendJson(final String phnNmbr, final String drink) {
Thread t = new Thread(){
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try{
HttpPost post = new HttpPost("http://kubie.dyndns-home.com/R2Bar2/sendOrder.php");
json.put("phone_number", phnNmbr);
json.put("drink_name", drink);
StringEntity se = new StringEntity( "orders: " + json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
Toast.makeText(getApplicationContext(), json.toString(), Toast.LENGTH_LONG).show();
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
}
catch(Exception e){
e.printStackTrace();
//createDialog("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
I had used the same method except for how you are trying to access json data on the server.
I had used $_POST array to access it and it worked well for me. Try using,
$json = $_POST['orders'];
$obj = json_decode($json);
This had worked perfectly well for me. All the best :)
(I dont think there is a problem with $handle since something is being inserted into the table)
I figured out what I was doing wrong. It seems as though I was passing in a raw data type. In order to parse the string, I used the following:
$obj = json_decode(file_get_contents("php://input"));
mysql_query("INSERT INTO orders (phone_number, drink_name)
VALUES ('".$obj->{'phone_number'}."', '".$obj->{'drink_name'}."')");
Thanks everyone for your suggestions.
You have make a connection to the DB as follws,you have missed the $handle to make connection
$handle = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$handle) {
die('Not connected : ' . mysql_error());
}
// make r2bar2 the current db
$db=mysql_select_db('r2bar2',$handle);
if (!$db) {
die ('Can\'t use r2bar2 : ' . mysql_error());
}