PHP inserts blank row into mysql table from android app - php

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();

Related

Sending a string from an app to a server

I have been working on an app which will send a string to a database on my server, however for some reason no data is received. Maybe you could point me in the right direction, I have been searching all over the net but can't find the reason why it's not working.
My android code:
public class HttpURLConnectionHandler
{
protected String urlG = "http://example.com/";
public String sendText(String text)
{
try {
URL url = new URL(urlG+"phpcode.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
DataOutputStream wr = new DataOutputStream(
conn.getOutputStream());
wr.writeBytes("mydata:"+text);
wr.flush();
wr.close();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
}
catch(Exception e){ return "error";}
}
}
My code in php:
<?php
$servername = "here is my server";
$username = "my username";
$password = "my pass";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$image = $_POST['image'];
$sql = "INSERT INTO photos (image)
VALUES ('{$image}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The way I call my class is:
HttpURLConnectionHandler handler= new HttpURLConnectionHandler();
String response = handler.sendText("this is a text");
I let you look around Retrofit
You trying to get value of POST variable image in your PHP, but you sending variable mydata.

Send json object to local php server using HttpURLConnection

I am trying to send json object in android to local php server(XAMPP).
Here is my php script which recieves that object.
<?php
$response = array();
if (isset(($_POST['PNR_NO'])&&($_POST['Status'])&&($_POST['update_time']))){
$PNR_NO = $_POST['PNR_NO'];
$Status = $_POST['Status'];
$update_time = $_POST['update_time'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO pnr_database(PNR_NO, Status,update_time) VALUES('$PNR_NO', '$Status', '$update_time')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
}
else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
}
else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}?>
And the java code that i am using is :
#Override
protected Void doInBackground(String... urls) {
OutputStream os;
HttpURLConnection conn = null;
try {
//constants
String pnr = "1234";
String stat = "WC12";
String updTime = "13:20";
Log.i("aaaaa", "Started");
URL url = new URL(urls[0]);
JSONObject jsonObject = new JSONObject();
jsonObject.put("PNR_NO",pnr );
jsonObject.put("Status", stat);
jsonObject.put("update_time", updTime);
String message = jsonObject.toString();
System.out.println(message);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /*milliseconds*/);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
//open
conn.connect();
//setup send
os = new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
Log.i("aaaaa","ended");
//clean up
os.flush();
}
catch (IOException e) {
e.printStackTrace();
}
catch (JSONException ex) {
ex.printStackTrace();
}
finally {
//clean up
/*try {
os.close();
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
*/
conn.disconnect();
}
return null;
}
Basically I want to send data to my php server where I have created a database which has a table named pnr_database and the sent data should get stored in that table.I don't want any response from server.
But my code is not working...
I tested my php script from a html form where i was sending data to server... In that case php script was working fine and data was getting stored in database But i am not able to make it work in android.
This might be a little late answer. But the JSON you receive in php is encoded so you need to decode it as such in your if clause:
$decoded = json_decode($_POST, true); //this will return an array
$PNR_NO = $decoded['PNR_NO'];
$Status = $decoded['Status'];
$update_time = $decoded['update_time'];
Here you can enter the columns to your table.

How to get a variable from php to android?

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());
}

Getting a single field from HTTP Response

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.

Connecting mysql database with Android app

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!

Categories