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);
Related
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);
}
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 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);
I am in a problem can any one help me please.
I have a php file which i am calling from my java class file's Asynctask.
In the Asynctask i am sending three variables email,password and pin.
What is happening, is that when i run my php with hardcoded values it gives me proper result.
RESULT IS:
Inside 1st if
Inside 2nd if
Verified
main if
But wen i try running my php through the code it gives me wrong result
RESULT IS:
Inside 1st if
Invalid
main if
I'am not able to understand why is this happening please Guide me.
My PHP File
<?php
require 'DbConnect.php';
$i=1;
$Password = $_POST["password"];
$Email = $_POST["email"];
$Pin = $_POST["pin"];
//$KeyCode = $_REQUEST["key"];
if((isset($_POST["password"])) && (isset($_POST["email"])) && (isset($_POST["pin"])))
{
$query4 = ("SELECT seller_id, name, email, password, verification_Pin, verification_Code, created_Date FROM `seller` WHERE email = '$Email'");
$query_run = mysql_query($query4);
$row=mysql_fetch_row($query_run);
$int=$row[0];
$strName=$row[1];
$strEmail=$row[2];
$strPwd=$row[3];
$strPin=$row[4];
echo $Pin;
echo $Password;
echo $Email;
echo $int;
echo $strEmail;
echo $strPwd;
echo $strPin;
if(($Email==$strEmail) && ($Password==$strPwd) && ($Pin==$strPin))
{
global $i;
$i=2;
$id=updateValidation($int);
echo $id;
if($id==1)
{
echo "Verified";
}
else
{
echo "Not Verified";
}
}
else
{
echo "Invaild";
}
}
else
{
echo "Values not set";
}
function updateValidation($sid)
{
global $i;
if($i==2)
{
echo "Inside Update vAlidation";
$queryUpdate = ("UPDATE `seller` SET verification_Pin = 0, verification_Code = 'Verified', created_Date = CURDATE() where seller_id='$sid'");
if(mysql_query($queryUpdate))
{
return 1;
}
else
{
return 2;
}
}
else
{
echo "i not 2";
}
}
?>
My Class file:
Button ok = (Button) myDialog
.findViewById(R.id.button1);
et_pin = (EditText) myDialog
.findViewById(R.id.editText1);
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"CLICKED OK", Toast.LENGTH_LONG).show();
pin = et_pin.getText().toString();
Toast.makeText(
getApplicationContext(),
"email,pass,pin= " + str1 + "," + str2
+ "," + pin, Toast.LENGTH_LONG)
.show();
new App_pin_Task().execute(FILENAME_pin);
// Intent intent = new
// Intent(Dealer_details.this,
// Login.class);
// startActivity(intent);
}
});
public class App_pin_Task extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(),
"Inside App_pin_Task post Execute(Result)=" + result,
Toast.LENGTH_LONG).show();
if (result.contains("Invalid")) {
et_pin.setText("");
} else {
Intent myIntent = new Intent(Login.this, UserActivity.class);
startActivity(myIntent);
}
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
// String is = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://animsinc.com/verifyEmail.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
4);
nameValuePairs.add(new BasicNameValuePair("email", str1));
nameValuePairs.add(new BasicNameValuePair("password", str2));
nameValuePairs.add(new BasicNameValuePair("pin", pin));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
}
return is;
}
}
What is being returned with
$Password = $_REQUEST["password"];
$Email = $_REQUEST["email"];
$Pin = $_REQUEST["pin"];
$KeyCode = $_REQUEST["key"];
Your server configuration may have this option disabled and not returning anything.
You shouldn't use $_REQUEST anyway because you can never be sure where the data is actually coming from: $_POST, $_GET or $_cookie.
try this!
Change this
$Password = $_REQUEST["password"];
$Email = $_REQUEST["email"];
$Pin = $_REQUEST["pin"];
$KeyCode = $_REQUEST["key"];
to for Get Request
$Password = $_GET["password"];
$Email = $_GET["email"];
$Pin = $_GET["pin"];
$KeyCode = $_GET["key"];
or for Post Request
$Password = $_POST["password"];
$Email = $_POST["email"];
$Pin = $_POST["pin"];
$KeyCode = $_POST["key"];
or
"SELECT seller_id, name, email, password, verification_Pin,
verification_Code, created_Date FROM seller WHERE email = '".$Email."'"
Complementing the answer from fayeq-ali-khan I would also do the following;
First use post and add html special character for security.
htmlspecialchars => Convert special characters to HTML entities
$Password = htmlspecialchars($_POST['password'],ENT_QUOTES);
$Email = htmlspecialchars($_POST['email'],ENT_QUOTES);
$Pin = htmlspecialchars($_POST['pin'],ENT_QUOTES);
$KeyCode = htmlspecialchars($_POST['key'],ENT_QUOTES);
Also on your android activity and before you send the string it would be a good idea to trim the value to make sure that you are not transmitting empty character that can also mess up with the PHP
nameValuePairs.add(new BasicNameValuePair("email", str1.trim()));
nameValuePairs.add(new BasicNameValuePair("password", str2.trim()));
nameValuePairs.add(new BasicNameValuePair("pin", pin.trim()));
I hope it help you with something