I am unable to insert data into my MySQL database. And I also have send reply back to Android Module to show if the data is saved or not.
PHP code:
$id = $_POST['Id'];
$name = $_POST['Name'];
$email = $_POST['Email'];
$con = new PDO("mysql:host=localhost;dbname=test", "root", "");
$query = "Insert into record values ('$id','$name','$email')";
//$query = "Select * from record";
$result = $con->query($query);
And Android code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new);
final EditText Id = (EditText) findViewById(R.id.editText);
final String id = Id.getText().toString();
final EditText Name = (EditText) findViewById(R.id.editText2);
final String name = Name.getText().toString();
final EditText Email = (EditText) findViewById(R.id.editText3);
final String email = Id.getText().toString();
Button SavePush = (Button) findViewById(R.id.button3);
SavePush.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.3.2:8080/insert.php");
try{
ArrayList NameValuePairs = new ArrayList<NameValuePair>(3);
NameValuePairs.add(new BasicNameValuePair("Id",id));
NameValuePairs.add(new BasicNameValuePair("Name", name));
NameValuePairs.add(new BasicNameValuePair("Email", email));
httpPost.setEntity(new UrlEncodedFormEntity(NameValuePairs));
HttpResponse response = httpclient.execute(httpPost);
}catch (Exception e){e.printStackTrace();}
}
});
}
Move your api call to asynctask or thread. You cannot use them in main ui thread.
First of all modify your php code like:
$id = htmlentities($_POST['Id']);
$name = htmlentities($_POST['Name']);
$email = htmlentities($_POST['Email']);
try{
$con = new PDO("mysql:host=localhost;dbname=test", "root", "");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(Exception $e){
echo $e->getMessage();
die();
}
$query = "INSERT INTO record VALUES('?','?','?')";
$result = $con->prepare($query);
$result = bindParam(?, $id);
$result = bindParam(?, $name);
$result = bindParam(?, $email);
$finalresult = $con->execute($result);
Related
I dont think I have anything deprecated in my code, when I run the PHP script I get the success, but nothing appears in the database.
Heres the PHP Code.
<?php include "../inc/dbinfo.inc"; ?>
<?php
$connect = new mysqli("DB_SERVER","DB_USERNAME","DB_PASSWORD","DB_DATABASE");
if(!$connect){
die('error');
}
else
{
echo "success";
}
$username = isset($_POST['username']) ? $_POST['username'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$givenname = isset($_POST['givenname']) ? $_POST['givenname'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$phonenumber = isset($_POST['phonenumber']) ? $_POST['phonenumber'] : '';
$sql = "INSERT INTO test(username,password,givenname,email,phonenumber) VALUES ('$username', '$password', '$givenname', '$email', '$phonenumber')";
mysqli_close($connect);
?>
Heres the Android Code.
private void insertToDatabase(){
class SendPostReqAsyncTask extends AsyncTask<String, Void,String >
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
String paramGivenname = params[2];
String paramEmail = params[3];
String paramPhonenumber = params[4];
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("givenname", givenName.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("email", email.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("phonenumber", phone.getText().toString()));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Constantss.DB_DNS);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
// sendPostReqAsyncTask.execute(uname,pword, gname, lmail,pnumb);
}
I get the success from the Android Code to, but nothing appears in the database table.
Does anyone know the problem? Thanks!
You didn't execute the query.
So use:
mysqli_query($connect, $sql); and check for errors on it also.
References:
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.error.php
Since another answer was given and I have pointed that out in comments first, just so we set the record straight.
You're also open to an sql injection. Use a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
You don't execute the query in your code. Also I would strongly suggest to sanitize the user input.
This asks for SQL injection. Consult: How can I prevent SQL injection in PHP?
Run the query:
$res = mysqli_query($connect, $sql);
I'm trying to read a php script URL through QR code and then retrieve MAC of device, after that, I want to send the MAC to php script but android app is crashing if I try it.
I'm also opening the url in a browser using intent. What should I write at php side to retrieve the MAC address and any changes in android activity?
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_decoder);
mydecoderview = (QRCodeReaderView) findViewById(R.id.qrdecoderview);
mydecoderview.setOnQRCodeReadListener(this);
myTextView = (TextView) findViewById(R.id.exampleTextView);
line_image = (ImageView) findViewById(R.id.red_line_image);
TranslateAnimation mAnimation = new TranslateAnimation(
TranslateAnimation.ABSOLUTE, 0f,
TranslateAnimation.ABSOLUTE, 0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0f,
TranslateAnimation.RELATIVE_TO_PARENT, 0.5f);
mAnimation.setDuration(1000);
mAnimation.setRepeatCount(-1);
mAnimation.setRepeatMode(Animation.REVERSE);
mAnimation.setInterpolator(new LinearInterpolator());
line_image.setAnimation(mAnimation);
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
/*String ur="http://192.168.0.105/project/rec.html";
Intent intent1=new Intent("android.intent.action.VIEW");
if (!ur.contains("http://"))
ur = "http://" + ur;
intent1.setData(Uri.parse(ur));
startActivity(intent1);// Perform action on click*/
}
});
}
// Called when a QR is decoded
// "text" : the text encoded in QR
// "points" : points where QR control points are placed
#Override
public void onQRCodeRead(String text, PointF[] points) {
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
action = wInfo.getMacAddress();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(addr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair(1);
nameValuePairs.add(new BasicNameValuePair("action",action));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = newBasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
String reverseString = response;
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
Intent localIntent = new Intent("android.intent.action.VIEW");
if (!text.contains("http://"))
text = "http://" + text;
addr=text;
localIntent.setData(Uri.parse(text));
startActivity(localIntent);
}
error_reporting(0);
include("db_config.php");
$response = array();
if (isset($_GET['id'])) {
$id = $_GET['id'];
$item = $_GET['item'];
$r = mysql_query("select Department_id from student where st_id = '$id'");
$row = mysql_fetch_array($r);
$Department_id = $row[0];
$r = mysql_query("select Subject_name from subject where Subject_code ='$item'");
$row = mysql_fetch_array($r);
$Subject_name = $row[0];
$result = mysql_query("INSERT INTO `sis_fyp`.`student-subject` (`st_id`, `Subject_code`, `Status`, `grade`, `Department_id`, `Subject_name`) VALUES ('$id', '$item', 'Repeat', 'W', '$Department_id', '$Subject_name');");
if ($result>0) {
$response["success"] = 1;
} else {
$response["success"] = 0;
}
// echoing JSON response
echo json_encode($response);
}
Just make a php script like above
and pass your url in and android like:
wwww.yoururl.com?id=$id&item=$item
I am trying to get All the list of names and surnames from a mysql database but only for a certain username and password by which an user is accessing the service.
I tried with the code below but it seems that is not working. Actually the JSONArray i get back is EMPTY.
Here my java code and Php code (which is on the server).
The whole code is working great if I don't filter by username and password so actually i receive back the list. But as I try to filter by username and password the JsonArray is Null.
Please I will appreciate any clue!
public class ApiConnector {
public JSONArray GetAllCustomers(User user){
String url = "http://giacomoci.co.uk/FetchallDataList.php";
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username", user.username));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
DefaultHttpClient httpClient = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(url);
JSONArray jsonArray = null;
try {
//DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpGet httpGet = new HttpGet(url);
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = httpClient.execute(post);
HttpEntity httpEntity = httpResponse.getEntity();
if(httpEntity != null){
try {
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response : ", entityResponse);
jsonArray = new JSONArray(entityResponse);
}catch (JSONException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
} catch (ClientProtocolException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return jsonArray;
}
}
And here my PHP code
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "SELECT name, surname FROM Contacts WHERE username = ? AND password = ?");
mysqli_stmt_bind_param($statement, "ss", $username, $password);
$user[] = array();
while($row = mysqli_fetch_assoc($statement)){
$user[] = $row;
}
echo json_encode($user);
mysqli_close($con);
So if I delete "Where username = ? AND password = ?" and the following line everything goes fine, but I get names and surnames for all the usernames and passwords, as I don't want. What's wrong with this code?
$username = $_POST["username"];
$password = $_POST["password"];
Replace those _POST with _GET
$username = $_GET["username"];
$password = $_GET["password"];
I have My databases on an xampp server and my activity and php file is given below. The problem in this page is that when I run application it always throws an exception. It always shows my last message that there is "Some problem is there." My submission date is due soon.
This is my Activity file
public class AdminLoginActivity extends Activity {
TextView username, password, message;
Button SignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_login);
StrictMode.enableDefaults();
username = (TextView) findViewById(R.id.adminusername);
password = (TextView) findViewById(R.id.adminpassword);
message = (TextView) findViewById(R.id.textView5);
SignIn = (Button) findViewById(R.id.adminloginbtn);
SignIn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
checkAdminData();
}
});
}
public void checkAdminData()
{
InputStream isr = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:1234/adminlogin.php");
try
{
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair> (2);
nameValuePairs.add(new BasicNameValuePair("username", username.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch (ClientProtocolException e)
{
Log.e("log_tag", "Error in Http connection " + e.toString());
message.setText("couldn't connect to database");
}
catch (IOException e)
{
}
String responseText = null;
try
{
String res = isr.toString();
// res = res.replaceAll("\\s+", "");
if (res.equals("1")) {
Intent i = new Intent(this, AdminMainPage.class);
startActivity(i);
}
else{
message.setText("Username or Password incorrect");
}
}
catch (Exception e)
{
Log.e("log_tag", "Sorry!! Incorrect Username or Password " + e.toString());
message.setText("Some problem is there");
}
}
}
PHP file:
<?php
$hostname_localhost ="localhost";
$database_localhost ="sibuilder";
$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['username'];
$password = $_POST['password'];
$query_search = "select * from login l, admin a where a.username = '".$username."' AND l.password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo 0;
}
else {
echo 1;
}
?>
If you want to use your php script instead json format, can refer these questions
Android: AsyncTask to make an HTTP GET Request? Make an HTTP request with android to handle the response. Using AsyncTask is recommended.
I'm trying to update a row in my database via my android app. My pulling from the database is working but I'm having trouble with the updating. My code for updating is as follows:
My AsyncTask class:
private class UpdateAnimalTask extends AsyncTask<Void, Void, Boolean>
{
#Override
protected Boolean doInBackground(Void... arg0)
{
try
{
ID = (EditText) findViewById(R.id.eTid);
Name = (EditText) findViewById(R.id.eTname);
Type = (EditText) findViewById(R.id.eTtype);
Breed = (EditText) findViewById(R.id.eTbreed);
Gender = (EditText) findViewById(R.id.eTgender);
Injuries = (EditText) findViewById(R.id.eTinjuries);
Treat = (EditText) findViewById(R.id.eTtreat);
String nM = Name.getText().toString();
String tP = Type.getText().toString();
String bR = Breed.getText().toString();
String gE = Gender.getText().toString();
String iN = Injuries.getText().toString();
String tR = Treat.getText().toString();
ArrayList<NameValuePair> up = new ArrayList<NameValuePair>();
up.add(new BasicNameValuePair("name", nM));
up.add(new BasicNameValuePair("type", tP));
up.add(new BasicNameValuePair("breed", bR));
up.add(new BasicNameValuePair("gender", gE));
up.add(new BasicNameValuePair("injuries", iN));
up.add(new BasicNameValuePair("treatment", tR));
String phpLink = "http://select.garethprice.co.za/update.php?name=" + nM;
Log.e("Test", up.toString());
dbUpdate(up, phpLink);
Log.e("Test", up.toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error in uploading " + e.toString());
Toast.makeText(getBaseContext(), "Error " + e.toString(), Toast.LENGTH_LONG).show();
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
if(result)
{
Toast.makeText(getBaseContext(), "Successfully updated", Toast.LENGTH_LONG).show();
}
}
}
My dbUpdate method which is being called inside my asynctask class:
public void dbUpdate(ArrayList<NameValuePair> data, String phpL)
{
InputStream iS = null;
try
{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(phpL);
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
iS = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection " + e.toString());
Toast.makeText(getBaseContext(), "Error " + e.toString(), Toast.LENGTH_LONG).show();
}
}
My php:
<?php
include_once 'db.php';
$con=mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)or die("cannot connect");
mysql_select_db(DB_DATABASE)or die("cannot select DB");
$nM = $_GET['name'];
$tP = $_POST['type'];
$bR = $_POST['breed'];
$gE = $_POST['gender'];
$iN = $_POST['injuries'];
$tR = $_POST['treatment'];
$sql = "UPDATE tbl_Animals SET animal_Type = '$tP', animal_Breed = '$bR', animal_Gender = '$gE', animal_Injuries = '$iN', animal_Treatments = '$tR' WHERE animal_Name = '$nM'";
echo "test: " . $nM . $tP . $bR . $gE . $iN . $tR;
mysql_query($sql,$con) or die("error: " . mysql_error());
mysql_close($con)
?>
Executing the asynctask in my update button:
public void Update(View v)
{
new UpdateAnimalTask().execute();
}
The android code is not breaking so I suspect it's something with the php because my toast pops up that says update successful in my onPostExecute.
Thank you in advance.