Android cannot insert into database string with accents and blank space - php

I´m having a problem with this string: "Não Vou". It means "I don´t go". I´m trying to insert it into database with php/json file.
When I remove blank space and ~ accent it works fine.
What I have tried:
changed iso-8859-1 to utf-8;
changed eclipse encoding to utf-8;
changed print(json_encode($flag)) to print(json_encode('utf8_encode', $flag));
Have read similar posts but any of them helped me.
public class insertNo extends AsyncTask<String, Boolean, Boolean>{
#Override
protected Boolean doInBackground(String... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("e_id", subString));
nameValuePairs.add(new BasicNameValuePair("Não Vou", no));
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://mywebsite.com/includes/insert_counter.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
inputStream = entity.getContent();
Log.e("pass 1", "connection success");
}catch(Exception e){
Log.e("Fail 1", e.toString());
Log.e("Invalid IP", e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
inputStream.close();
result = stringBuilder.toString();
Log.e("pass 2", "connection success");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONObject json_data = new JSONObject(result);
code = (json_data.getInt("code"));
if (code==1) {
Log.d("Insert success", result);
} else {
Log.d("Sorry son", result);
}
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
return null;
}
}
php file
include_once("db_connect.php");
$e_id = $_REQUEST["e_id"];
$yes = $_REQUEST["Vou"];
$no = $_REQUEST["Não Vou"];
$maybe = $_REQUEST["Talvez"];
$flag['code']=0;
if(isset($yes)){
$r = mysqli_query($mysqli, "UPDATE table1 SET yes = yes + 1 WHERE id='$e_id'");
$flag['code']=1;
}else if(isset($no)){
$r = mysqli_query($mysqli, "UPDATE table1 SET no = no + 1 WHERE id='$e_id'");
$flag['code']=1;
}else if(isset($maybe)){
$r = mysqli_query($mysqli, "UPDATE table1 SET maybe = maybe + 1 WHERE id='$e_id'");
$flag['code']=1;
}
print(json_encode($flag));
mysqli_close($mysqli);

From the documentation, PHP variables should not contain special characters, or spaces, or anything out of
a letter is a-z, A-Z, and the bytes from 127 through 255 (0x7f-0xff).

Related

No Error : Data is not inserting in PHP MySql from Android

Data is not inserting in MySql from android there is no error in the code, i have defined them using AsyncThread - doInBackground and onPostExecute..Its showing the toast what i have defined in Json Object Try Catch Method 'Sorry Try Again' in else condition if data is not inserted.
InputStream is = null;
String res = null;
String line = null;
int code;
onClick Code
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
question = addque.getText().toString();
choice1 = addc1.getText().toString();
choice2 = addc2.getText().toString();
choice3 = addc3.getText().toString();
answer = addanswer.getText().toString();
Explanation = addexplan.getText().toString();
AsyncTaskRunner Class
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("question", question));
nameValuePairs.add(new BasicNameValuePair("choice1", choice1));
nameValuePairs.add(new BasicNameValuePair("choice2", choice2));
nameValuePairs.add(new BasicNameValuePair("choice3", choice3));
nameValuePairs.add(new BasicNameValuePair("answer", answer));
nameValuePairs.add(new BasicNameValuePair("Explanation",
Explanation));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://192.168.43.4/insert/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
res = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try
{
JSONObject json_data;
json_data = new JSONObject(res);
code = json_data.getInt("code");
if(code==1)
{
Toast.makeText(getActivity(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
}
PHP Code
<?php
$host='localhost';
$uname='root';
$pwd='';
$db="quizDB";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$question=$_REQUEST['question'];
$choice1=$_REQUEST['choice1'];
$choice2=$_REQUEST['choice2'];
$choice3=$_REQUEST['choice3'];
$answer=$_REQUEST['answer'];
$Explanation=$_REQUEST['Explanation'];
$flag['code']=0;
if($r=mysql_query("insert into quizquestion values('$question','$choice1',
$choice2, '$choice3', '$answer', '$Explanation') ",$con))
{
$flag['code']=1;
echo"hi";
}
print(json_encode($flag));
mysql_close($con);
?>
Correct me if i am wrong.
first get all string you want to insert and then call AsyncTask. may be this solve .
question = addque.getText().toString();
choice1 = addc1.getText().toString();
choice2 = addc2.getText().toString();
choice3 = addc3.getText().toString();
answer = addanswer.getText().toString();
Explanation = addexplan.getText().toString();
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
and also change this 2 line . pass UTF-8 to UrlEncodeFormEntity
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
httppost.setEntity(formEntity);
Edited
I think you forget to add concatination onto $choice2 , and change query like this. pass first fieldName and then Values.
$sql = "INSERT INTO MyGuests (fieldName1, fieldName2, fieldName3,fieldName4,fieldName5,fieldName6)
VALUES ('$question','$choice1','$choice2', '$choice3', '$answer', '$Explanation')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
$flag['code']=1;
echo"hi";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

Save the id only of a row in the SQLite android database

My android app is getting & writing data to the server and to the SQlite database.
I am fetching values for jobaddress.id = 1from server using a query (below). The values in SELECTstatement are displaying perfectly in the UI of android app however when I press "Save", instead of values from the server, I need to save the id 1 from the server in the local database without shwoing the id in the UI.
PHP sript (query only) for retrieving data from server:
$tsql = "SELECT tbl_manufacturers.manufacturers_name, tbl_appliances_models.appliances_models_name, tbl_appliances.appliances_serial, tbl_appliances.appliances_id, jobaddress.id
FROM jobaddress INNER JOIN
tbl_appliances ON jobaddress.id = tbl_appliances.appliances_jobaddress_id LEFT OUTER JOIN
tbl_appliances_models INNER JOIN
tbl_manufacturers ON tbl_appliances_models.appliances_models_manufacturers_id = tbl_manufacturers.manufacturers_id ON
tbl_appliances.appliances_models_id = tbl_appliances_models.appliances_models_id
WHERE (tbl_appliances.appliances_companies_id = 1) AND (jobaddress.id = 1)";
Showing data using JSON Parser:
public void getJobAddress()
{
String result = null;
InputStream isr = null;
try
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://datanetbeta.multi-trade.co.uk/tablet/getJobAddress.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e)
{
Log.e("Log_tag", "Error in hhtp connection " + e.toString());
}
//convert Response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result " + e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0; i < jArray.length(); i++)
{
JSONObject json = jArray.getJSONObject(0);
s = json.getString("address1");
t = json.getString("address2");
u = json.getString("postcode");
}
tvJbAddrs1.setText(s);
if(t == null)
{
tvJbAddrs2.setText("");
}
else
{
tvJbAddrs2.setText(t);
}
tvJbPostcode.setText(u);
}
catch (Exception e)
{
Log.e("log_tag", "Error Parsing Data " + e.toString());
}
} //getJobAddress() ends

insert data to mysql database from android app

xxxI am trying to insert data in mysql database from my Android app using php file. I don´t know what I am doing wrong, here is my android code:
public void insert()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nick",nick));
nameValuePairs.add(new BasicNameValuePair("minuto",minuto));
nameValuePairs.add(new BasicNameValuePair("id_pelicula",String.valueOf(id_pelicula)));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxx.xxxxx.com/xxxx/insertar.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "Opinión enviada correctamente",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Disculpe, inténtelo de nuevo",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
and here is my php file code:
<?php
// Connection data
$host = 'xxx.xxx.com';;
$uname = 'uxxxx';
$pwd = 'xxxxx';
$db = 'xxxxx';
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$nick=$_REQUEST['nick'];
$minuto=$_REQUEST['minuto'];
$id_pelicula=$_REQUEST['id_pelicula'];
$flag['code']=0;
if($r=mysql_query("insert into opiniones values('$nick','$minuto','$id_pelicula') ",$con))
{
$flag['code']=1;
echo"hi";
}
print(json_encode($flag));
mysql_close($con);
?>
Perhaps is because in my mysql database the "minuto" variable is integer and I use like String from android? Please somebody can help me? Thank you so much
I have solved, I had an error in the php file in this sentence:
if($r=mysql_query("insert into opiniones (nick, minuto, id_pelicula) values('$nick','$minuto','$id_pelicula') ",$con))

Sending and receiving json from android app to php script?

I am new to android development and I am trying to make a login page which sends the password and username to a php script as a json array and the php script returns a json array response which contains the meassage accordingly.
I have made a android code as:
jobj.put("uname", userName);
jobj.put("password", passWord);
JSONObject re = JSONParser.doPost(url, jobj);
Log.v("Received","Response received . . ."+re);
// Check your log cat for JSON reponse
Log.v("Response: ", re.toString());
int success = re.getInt("success");
if (success == 1) {
return 1;
}
else{
return 0;
}
}
catch(Exception e){ e.getMessage(); }
}
The JsonParser doPost code is as follows:
public static JSONObject doPost(String url, JSONObject c) throws ClientProtocolException, IOException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
HttpEntity entity;
StringEntity s = new StringEntity(c.toString());
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
entity = s;
request.setEntity(entity);
Log.v("entity",""+entity);
HttpResponse response;
try{
response = httpclient.execute(request);
Log.v("REceiving","Received . . .");
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
Log.v("RESPONSE",""+is);
}
catch(Exception e){
Log.v("Error in response",""+e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
Log.v("Reader",""+reader.readLine());
while ((line = reader.readLine()) != null) {
Log.v("line",""+line);
sb.append(line + "\n");
}
Log.v("builder",""+sb);
is.close();
json = sb.toString();
} catch (Exception e) {
Log.v("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.v("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I have the php script as:
$response = array();
$con=mysqli_connect("localhost","uname","password","db_manage");
if((isset($_POST['uname']) && isset($_POST['password']))){
$empid = $_POST['uname'];
$pass = $_POST['password'];
$query = "SELECT mm_emp_id,mm_password FROM employee_master WHERE mm_emp_id='$empid'and mm_password='$pass'";
$result = mysqli_query($con, $query);
if(count($result) > 0){
$response["success"] = 1;
$response["message"] = "";
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "The username/password does not match";
echo json_encode($response);
}
}
I am getting undefined index at the line where I check for isset(). What am I doing wrong in receiving the json in php script?
If you can see I have used a link for my help
Please do help me out.
In the doPost method you don't use the JSON object (JSONobject c) that contains the variables
public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {
String url = "http://test.myhodo.in/index.php/test/execute";
#Override
protected JSONObject doInBackground(JSONObject... data) {
JSONObject json = data[0];
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
JSONObject jsonResponse = null;
HttpPost post = new HttpPost(url);
try {
StringEntity se = new StringEntity("json="+json.toString());
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(se);
HttpResponse response;
response = client.execute(post);
String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
jsonResponse=new JSONObject(resFromServer);
Log.i("Response from server", jsonResponse.getString("msg"));
} catch (Exception e) { e.printStackTrace();}
return jsonResponse;
}
Main Activity
try {
JSONObject toSend = new JSONObject();
toSend.put("msg", "hello");
JSONTransmitter transmitter = new JSONTransmitter();
transmitter.execute(new JSONObject[] {toSend});
} catch (JSONException e) {
e.printStackTrace();
}

android username password send through json to php-->sql

im trying to find a way to post username and password using json rather than normal http post that im currently using. i have being going through most of the tutorials and examples to undestand but yet i was unable to get an idea. i have json phasers available to get the data from my sql but not the post json.
thank you for the help
following is the currently used json post
EditText uname = (EditText) findViewById(R.id.log_Eu_name);
String username = uname.getText().toString();
EditText pword = (EditText) findViewById(R.id.log_Epass);
String password = pword.getText().toString();
String result = new String();
result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs
.add(new BasicNameValuePair("username", username));
nameValuePairs
.add(new BasicNameValuePair("password", password));
InputStream is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.loshwickphotography.com/log.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.w("SENCIDE", "Execute HTTP Post Request");
String str = inputStreamToString(
response.getEntity().getContent()).toString();
Log.w("SENCIDE", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("SENCIDE", "TRUE");
Toast.makeText(getApplicationContext(),
"FUking hell yeh!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Sorry it failed", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
if (result != null) {
JSONArray jArray = new JSONArray(result);
Log.i("log_tag", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
}
} else {
Toast.makeText(getApplicationContext(), "NULL",
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
private Object inputStreamToString(InputStream is) {
// TODO Auto-generated method stub
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(
new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
});
Is this correct which i have written?
how to write the Php for this?
use this
JSONObject myjson=new JSONObject();
myjson.put("userName", "someOne");
myjson.put("password", "123");
and StringEntity se = new StringEntity(myjson.toString());
and httpPost.setEntity(se);

Categories