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.
Related
I am inserting json data from my android app in my device into xampp server in my computer using POST. It simply inserts row with empty column. When I enter the column from my browser using GET it converts it to numbers only eventhough the data is mix of numbers and letters. The type of the table column is varbinary. I entered 'crap' from my browser and it was inserted as '63726170' in the table. I am puzzled by this. Here is the PHP code that inserts the data.
if (isset($_POST)){
//sanitize the input
filter_var_array($_POST);
$ri=$_POST['regID'];
$id=json_decode($ri);
//$decoid= $id->regID;
if(is_array($id)){
foreach ($id as $key=>$value){
$fu=$id[$key];
};
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO regids (regID)
VALUES ('$fu')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
}else{
echo "Error executing query!!!";
}
$conn = null;
I am adding my android code that is sending the data to the server
URL url;
HttpURLConnection urlConn;
DataOutputStream printout;
url = new URL ("myurlhere");
urlConn = (HttpURLConnection)url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.setRequestMethod("POST");
urlConn.connect();
/*List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("regID", result));*/
String result = args.toString();
try{
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("regID", result);
String postData="json="+jsonParam.toString();
// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeUTF(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
Log.i("NOTIFICATION", "Data Sent");
printout.flush ();
printout.close ();
OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
os.write(postData);
Log.i("NOTIFICATION", "Data Sent");
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String msg="";
String line = "";
while ((line = reader.readLine()) != null) {
msg += line; }
Log.i("msg=",""+msg);
os.close();
I have written PHP code to fetch data from Database. It get the login values. (username & password). I connect it through mysql server/localhost. when I run this PHP code it always show the "0". It means it doesn't get the data from Database. Why is that?
Here my PHP code:
<?php
$hostname_localhost ="localhost";
$database_localhost ="gpsvts_geotrack";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['uname'];
$password = $_POST['passwd'];
$query_search = "select 'uname' & 'passwd' from user_master where uname = '.$username.' AND passwd = '.$password.'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "No Such User Found";
}
else {
echo "User Found";
}
?>
I put this in my wamp server www folder.when i run this php file wamp server localhost it always say "no such user found".
i used this php file for fetching data from db to connect android login form. it contain two fields. which are username & password.
here I give my android login code.
b = (Button)findViewById(R.id.Button01);
et = (EditText)findViewById(R.id.username);
pass= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(AndroidPHPConnectionDemo.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
}
void login(){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2//new/nuwan1.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
// edited by James from coderzheaven.. from here....
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
tv.setText("Response from PHP : " + response);
dialog.dismiss();
}
});
if(response.equalsIgnoreCase("User Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(AndroidPHPConnectionDemo.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
startActivity(new Intent(AndroidPHPConnectionDemo.this, UserPage.class));
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
AndroidPHPConnectionDemo.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(AndroidPHPConnectionDemo.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
Always I got the alart no such user found & php response is No such user found
why is that?
pls help me.
I used following php code
<?php
$un=$_POST['uname'];
$pw=$_POST['passwd'];
//connect to the db
$host="localhost"; // Host name
$user="root"; // Mysql username
$pswd=""; // Mysql password
$db="gpsvts_geotrack"; // Database name
$tbl_name="user_master"; // Table name
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db, $conn);
//run the query to search for the username and password the match
$query = "SELECT * FROM $tbl_name WHERE uname = '$un' AND passwd= '$pw'";
//$query = "SELECT uid FROM $tbl_name WHERE uname = '$un' AND passwd = '$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 mysql_result($result,0); // for correct login response
else
echo 0; // for incorrect login response
?>
Then return uid as response. but not validating user. Is there PHP code wrong or android code wrong. I want to match the values user enter & database get. Is that happen in here.
if not give me correct thing.
In your program you are passing from your side is:
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
And you are trying to fetch from PHP side is:
$un=$_POST['uname'];
$pw=$_POST['passwd'];
So Change The Name in nameValuePairs are passed with this:
nameValuePairs.add(new BasicNameValuePair("uname",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("passwd",pass.getText().toString().trim()));
If I'm not mistaken it should be like this because your post variables are spelled different than what you're putting in the name value pairs.
nameValuePairs.add(new BasicNameValuePair("uname",et.getText().toString().trim())); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("passwd",pass.getText().toString().trim()));
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 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());
}
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.