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 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'm comparing the username and password from the user input to the database data, and I used count to check if it is equal to 1 or 0.
If it's equal to 1, the editText should be set to 1, and if it's 0 it should be set to 0.
My problem is, it's always set to 0 even if the username and password is correct.
here is the name value pair and connection to the database:
username = etlogUsername.getText().toString();
password = etlogPassword.getText().toString();
String output = "";
//setting the NameValuePair
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
//adding the string variables inside the nameValuePairs
nameValuePairs.add(new BasicNameValuePair("user_username", username));
nameValuePairs.add(new BasicNameValuePair("user_password", password));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://thesis-account.byethost7.com/workout_select_username.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//getting the response
HttpResponse response = httpclient.execute(httppost);
//setting up the entity
HttpEntity entity = response.getEntity();
is = entity.getContent();
here is the json that will read the data:
JSONArray jArray= new JSONArray(output);
for(int i = 0; i <jArray.length() ; i++){
JSONObject json = jArray.getJSONObject(i);
COUNT_user_id = json.getInt("num_rows");
if(COUNT_user_id == 1)
{
isEqual = true;
}
}
etlogUsername.setText(COUNT_user_id+"");
and here is the php file:
$sql = mysql_query("SELECT COUNT(user_id) AS num_rows FROM tbl_users
WHERE user_username='{ $username}' && user_password = '{$password}' ");
while($row=mysql_fetch_assoc($sql))
{
$output[]=$row;
}
print(json_encode($output));
mysql_close($con);
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 trying to get all the Json data into my Mysql database through php, I have all my phone contacts details in this json object, But It only insert just one last phone contact detail to my database, please help as I have already posted a question but did not find a satisfactory answers. I debugged the application and it contains all of my contact detail in params of makehttprequest(.....)function, but Insert only last contact detail into database.
My php code is given below:
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['id']) && isset($_POST['phone'])&& isset($_POST['email'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
// 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 crm(id, name, phone, email) VALUES('$id', '$name', '$phone', '$email')");
// 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 {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
My json object Which I copied during debugging the application is:
[id=85, name=, phone=, email=2, id=106, name=, phone=, email=2, id=93, name=, phone=, email=2, id=62, name=., phone=*100#, email=2, id=104, name=00, phone=00, email=2, id=90, name=03005103877, phone=03005103877, email=2, id=26, name=03005580234, phone=03005580234, email=2, id=154, name=Wajaht, phone=+923336124178, email=2, id=230, name=Yasir Altaf, phone=03215169284, email=2, id=55, name=Zafar Abbas, phone=03016775189, email=2]
But It it inserted the last contact detail which is name=Zafar Abbas, phone=03016775189, email=2 But I want insert all the detail in one go, please help me Thanks
AYsync task Class:
public class LoadSavingInDatabase extends AsyncTask<ArrayList<SavingContacts>,String,String>{
private static final String TAG_SUCCESS = "success";
private static final String URL = "http://amiranzur.com/android_connect/create_product.php";
JSONObject jsonObject= null;
#Override
protected String doInBackground(ArrayList<SavingContacts>... param) {
ArrayList<SavingContacts> contactArray = param[0];
List<NameValuePair> params = new ArrayList<NameValuePair>();
for(int i = 0; i < contactArray.size(); i++){
SavingContacts contact = contactArray.get(i);
params.add(new BasicNameValuePair("id", contact.id));
params.add(new BasicNameValuePair("name", contact.name));
params.add(new BasicNameValuePair("phone", contact.phone));
params.add(new BasicNameValuePair("email" , contact.email ));
}
JSONObject jsonObject= new JSONParser().makeHttpRequest(URL, "POST", params);
if(jsonObject != null){
try {
int success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("create","ok2");
bool = true;
Log.d("insert","true" + bool);
} else {
}
} catch (JSONException e) {
Log.d("exception","exc "+e);
Log.d("create","lpc");
}
}
else if(jsonObject == null){
Log.d("null", "null1");
bool = false;
}
return null;
}
}
protected void onPostExecute(boolean bool){
if(bool == false)
Log.d("Insertion failed", "ID already inserted");
}
Json P arser Class:
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
Log.d("Hope","Hope 1");
url += "?" + paramString;
Log.d("Hope","Hope 2");
HttpGet httpGet = new HttpGet(url);
Log.d("Hope","Hope 3");
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.d("Hope","Hope 4");
HttpEntity httpEntity = httpResponse.getEntity();
Log.d("Hope","Hope 5");
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
Log.d("ex1","ex1 "+e);
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.d("ex1","ex2 "+e);
e.printStackTrace();
} catch (IOException e) {
Log.d("ex1","ex3 "+e);
e.printStackTrace();
}
try {
Log.d("Hope","Hope 6");
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
Log.d("Hope","Hope 7");
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
Log.d("Hope","Hope 8");
is.close();
json = sb.toString();
Log.d("eee","json"+ json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + json);
}
//char[] chars = json.toCharArray();
// try parse the string to a JSON object
//if(chars[0] != 'D'){
try {
jObj = new JSONObject(json);
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
//}
//else {
// Log.d("null","null");
// }
return jObj;
}
}
The problem is here:
for(int i = 0; i < contactArray.size(); i++){
SavingContacts contact = contactArray.get(i);
params.add(new BasicNameValuePair("id", contact.id));
params.add(new BasicNameValuePair("name", contact.name));
params.add(new BasicNameValuePair("phone", contact.phone));
params.add(new BasicNameValuePair("email" , contact.email ));
}
JSONObject jsonObject= new JSONParser().makeHttpRequest(URL, "POST", params);
You make the request only after the loop,that will explain why you only INSERT the last value.
Move the request inside the loop so that you perform an insert at each iteration:
bool isSuccessful;
for(int i = 0; i < contactArray.size(); i++){
SavingContacts contact = contactArray.get(i);
params.add(new BasicNameValuePair("id", contact.id));
params.add(new BasicNameValuePair("name", contact.name));
params.add(new BasicNameValuePair("phone", contact.phone));
params.add(new BasicNameValuePair("email" , contact.email ));
//INSERT at each iteration
JSONObject jsonObject= new JSONParser().makeHttpRequest(URL, "POST", params);
if(jsonObject != null){
try {
int success = jsonObject.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("debug", "Contact Id# " + contact.id +" Inserted");
} else {
Log.d("debug", "Contact Id# " + contact.id +" FAILED");
}
isSuccessful = true;
} catch (JSONException e) {
Log.d("exception","exc "+e);
Log.d("create","lpc");
isSuccessful = false;
}
}else{
Log.d("debug", "json is null");
isSuccessful = false;
}
}
return isSuccessful;