android uploading empty image to the host using php - php

I'm trying to upload a photo from an android device to host using PHP and base 64, bitmap ; but it uploads two empty images (it uploads two times) can't figure out why, any help or alternative way?
I'm uploading the photo in a register layout so I tried just inserting the photo without anything else, and I tried using another hosting service but unfortunately, nothing worked.
the name of the empty photo is inserted in the database yet in the file manager it's an empty photo
the php code;
<?php
// array for JSON response
$response = array();
$user_image= $_POST['user_image'];
$user_name= $_POST['user_name'];
$user_email= $_POST['user_email'];
$user_un= $_POST['user_un'];
$user_pass= $_POST['user_pass'];
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
$ra=rand(0,20000);
$rn=rand(0,40000);
$rd=rand(0,60000);
$imgname = "pl".$ra.$rn.$rd.".jpeg";
$decoding=base64_decode("$user_image");
file_put_contents("images/".$imgname,$decoding);
$sql = "INSERT INTO Users (user_name,user_email,user_un,user_pass,user_image)
VALUES ('$user_name','$user_email','$user_un','$user_pass','$imgname')";
if ($conn->query($sql) === TRUE) {
$UserId = $conn->insert_id;
$response['dishs'] = array();
$hobbie['status'] = "ok";
$hobbie['result'] = "Welcome";
// push single dishinto final response array
array_push($response['dishs'],$hobbie);
// echoing JSON response
echo json_encode($response);
} else {
// echo "Error: " . $sql . "" . $conn->error;
$response['dishs'] = array();
// failed to insert row
$hobbie['status'] = "no";
$hobbie['result'] = "Error: " . $sql . "" . $conn->error;
array_push($response['dishs'],$hobbie);
// echo no users JSON
echo json_encode($response);
}
}
$conn->close();
?>
the kotlin code
these are defined in the head of the class
"class RegisterPage :Fragment() {
var encodImg = ""
var bitmap: Bitmap? = null
......
"
sending this to the host
"... val params = HashMap<String, String>()
params["user_image"] = encodImg
...
"
the way i choose the photo from gallery and encrypt
private fun startGallery() {
val galleryIntent = Intent(Intent.ACTION_GET_CONTENT)
galleryIntent.type = "image/*"
if (galleryIntent.resolveActivity(activity!!.packageManager) != null) {
startActivityForResult(galleryIntent, 1000)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, i: Intent?) {
super.onActivityResult(requestCode, resultCode, i)
if (resultCode == Activity.RESULT_OK) {
val uri: Uri? = i!!.data
change_profile_photo.setImageURI(uri)
manageImageFromUri(i.data!!)
} else {
Toast.makeText(activity, "Error", Toast.LENGTH_LONG).show()
}
}
private fun manageImageFromUri(imageUri: Uri) {
val baos = ByteArrayOutputStream()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Snackbar.make(view!!, "ERROR", Snackbar.LENGTH_LONG)
} else {
bitmap = MediaStore.Images.Media.getBitmap(activity?.contentResolver, imageUri)
bitmap!!.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
encodImg = Base64.encodeToString(b, Base64.DEFAULT)
}
}
}

Related

Only output invalid YouTube ID's from database if video doesn't exists

I have YouTube video IDs stored in my database. I'm trying to output the IDs that are only invalid. I'm using get_headers / oembed which allows me to check if a video exists on YouTube. Then I am looping through the ID's. This is currently working but it's showing all YouTube IDs from my table and then adding the text "is invalid" to the ones that are invalid. I need to only display the ones that are invalid - nothing else!
I could use some help if anyone wouldn't mind. I would really appreciate it.
Code:
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT src_id FROM youtube_videos ";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo 'Video ID: '.$row["src"];
$headers = get_headers('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v='.$row["src_id"].'');
if (!strpos($headers[0], '200')) {
echo " is invalid";
} else {
echo "";
}
echo 'no results';
}
Just print the video ID if the header code is not 200?
while ($row = $result->fetch_assoc()) {
$headers = get_headers('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v='.$row["src_id"].'');
if (!strpos($headers[0], '200')) {
echo "Video ID: ".$row['src']." is invalid\n";
}
}
Might also want to look into a better way of grabbing response-headers, that thing might not be 100% accurate for all scenarios. I would suggest using something like
while ($row = $result->fetch_assoc()) {
$headers = get_headers('http://www.youtube.com/oembed?url=http://www.youtube.com/watch?v='.$row["src_id"].'');
if (substr($headers[0], 9, 3) != 200) {
echo "Video ID: ".$row['src']." is invalid\n";
}
}

Unity and MySQL can't register many Chinese

I am making register and log in .
When I input over two Chinese words , it's can't register.
Only one Chinese word can register.
I add the Chinese words to username from phpMyadmin and it can log in!
Why I can't register many Chinese at start?
please help me !
PHP:
<?php
$con = mysqli_connect('xxxx:3306', 'root', 'xxxx', 'xxxx');
if(mysqli_connect_errno())
{
echo "1: Connection failed";
exit();
}
$username = $_POST["name"];
$password = $_POST["password"];
$gender = $_POST["gender"];
$namecheckquery = "SELECT username FROM players WHERE username='" . $username . "';";
$namecheck = mysqli_query($con, $namecheckquery) or die("2: Name check query failed");
if (mysqli_num_rows($namecheck) > 0)
{
echo "3:Name already exists";
exit();
}
$salt = "\$5\$rounds=5000\$" . "steamedhams" . $username . "\$";
$hash = crypt($password, $salt);
$insertuserquery = "INSERT INTO players (username, hash,salt,gender) VALUES
('" . $username."', '" . $hash . "', '". $salt."','".$gender."');";
mysqli_query($con, $insertuserquery) or die ("4: Insert player query failed");
echo ("0"); ?>
My code in Unity
public class Registration : MonoBehaviour
{
public InputField nameField;
public InputField passwordField;
public Button submitButton;
public Button boyButton;
public Button girlButton;
public void CallRegister()
{
StartCoroutine(Register());
}
IEnumerator Register()
{
WWWForm form = new WWWForm();
form.AddField("name", nameField.text);
form.AddField("password", passwordField.text);
WWW www = new WWW("http://localhost/sqlconnect/register.php", form);
yield return www;
if(www.text =="0")
{
Debug.Log("User created successfully");
UnityEngine.SceneManagement.SceneManager.LoadScene("mainmenu");
}
else
{
Debug.Log("User creation failed. Error #" + www.text);
}
}
public void VerifyInputs()
{
submitButton.interactable = (nameField.text.Length >= 1 && passwordField.text.Length >= 4);
}
}
I'm not sure but my guess would be that WWW does not automatically escape spaces in the provided form or have encoding errors.
In general you should try and rather use UnityWebRequest.Post which clearly states:
The data in postData will be escaped, then interpreted into a byte stream via System.Text.Encoding.UTF8.
which might solve your problem
private IEnumerator Register()
{
WWWForm form = new WWWForm();
form.AddField("name", nameField.text);
form.AddField("password", passwordField.text);
using(var www = UnityWebRequest.Post("http://localhost/sqlconnect/register.php", form))
{
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.Log(www.error);
return;
}
if(string.Equals(www.downloadHandler.text, "0"))
{
Debug.Log("User created successfully");
UnityEngine.SceneManagement.SceneManager.LoadScene("mainmenu");
}
else
{
Debug.Log("User creation failed. Error #" + www.text);
}
}
}

org.json.JSONException: End of input at character 0 of with volley and php

yesterday I came across the error mentioned below, so I started looking for similar questions on stackoverflow...but none of them seemed to help:(
My guess is that im getting no response from the server but I cant come up with an idea how to fix that. Im using like the same code in some other activities (of course with other functions) but al of them are working perfectly fine.
The only thing that changed is that I used Update table for the first time but I cant see how that would result in the following error.
I hope you can help me.
The strange thing is if the
$anzahlrows == 1
is true and there is no more error in the php file with the query (like usual) than I get in android:
Register Response: {"success":true,"error_msg":"Sie wurden erfolgreich angelegt!"}
I/jsonResponse: {"success":true,"error_msg":"Sie wurden erfolgreich angelegt!"}
and everything works fine....
This is the error im getting:
org.json.JSONException: End of input at character 0 of
in the line of
JSONObject jsonResponse = new JSONObject(response);
This is the code in android studio:
Response.Listener<String> responseListener = new Response.Listener<String>() {
// this gets called on response
#Override
public void onResponse(String response) {
Log.d("Response:", "Register Response: " + response);
// check for boolean success from php
try {
JSONObject jsonResponse = new JSONObject(response);
Log.i("jsonResponse", jsonResponse.toString());
boolean success = jsonResponse.getBoolean("success");
// if true from php start LoginActivity
if (success){
Toast.makeText(RegisterActivity.this, jsonResponse.getString("error_msg"), Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
RegisterActivity.this.startActivity(intent);
}
// if false build an AlertDialog
else {
Toast.makeText(RegisterActivity.this, jsonResponse.getString("error_msg"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
// call register request and transfer string username and password
RegisterRequest registerRequest = new RegisterRequest(email, password, matrikelnummer, firstName, surname, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
This is my PHP File:
if (isset($_POST["email"]) or isset($_POST["password"]) or isset($_POST["matrikelnummer"]) or isset($_POST["firstName"]) or isset($_POST["surname"])) {
$email = $_POST["email"];
$password = $_POST["password"];
$matrikelnummer = $_POST["matrikelnummer"];
$firstName = $_POST["firstName"];
$surname = $_POST["surname"];
$query = "SELECT * FROM Users WHERE Matrikelnummer ='$matrikelnummer'";
if ($result=mysqli_query($con,$query)) {
$anzahlrows = mysqli_num_rows($result);
if($anzahlrows == 1) {
$query = "UPDATE Users SET email = '$email' ,password = '$password',firstName = '$firstName', surname = '$surname' WHERE Matrikelnummer = '$matrikelnummer'";
if ($result=mysqli_query($con,$query)) {
$response["success"] = TRUE;
$response["error_msg"] = "Sie wurden erfolgreich angelegt!";
echo json_encode($response);
exit;
} else {
$response["success"] = FALSE;
$response["error_msg"] = "Fehler bei der INSERT SQL Abfrage";
echo json_encode($response);
exit;
}
}
else {
$response["success"] = FALSE;
$response["error_msg"] = "Die angegebene Matrikelnummer ist nicht verfügbar";
echo json_encode($response);
exit;
}
}
else {
$response["success"] = FALSE;
$response["error_msg"] = "Fehler bei der SQL Abfrage";
echo json_encode($response);
exit;
}
}
else {
$response["success"] = FALSE;
$response["error_msg"] = "Required parameters missing!";
echo json_encode($response);
exit;
}
The Log shows following:
D/Response:: Register Response:
W/System.err: org.json.JSONException: End of input at character 0 of
W/System.err: at org.json.JSONTokener.syntaxError(JSONTokener.java:449)
W/System.err: at org.json.JSONTokener.nextValue(JSONTokener.java:97)
W/System.err: at org.json.JSONObject.<init>(JSONObject.java:156)
.
.
.
I usually create a response in my PHP code before my code enters the if (isset($_POST["email"]) code starts. Then at each if/else statement I create an appropriate response-- just as you have, with the exception that I do not echo the response and exit. My final statement is where I use the echo response such that it will echo my response regardless of what happens between.
<?php
// array for JSON response
$response = array();
$response["success"] = 0;
$response["message"] = "Error before Parameters";
// check for post data
if (isset($_POST["id"])) {
$id = $_POST['id'];
// include db connect class
require_once __DIR__ . '/db_config.php';
// set vars
$host = DB_SERVER;
$db = DB_DATABASE;
$user = DB_USER;
$pass = DB_PASSWORD;
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// connecting to db
$pdo = new PDO($dsn, $user, $pass, $opt);
$sql = 'SELECT * FROM tblConnectionData WHERE ID = :id;';
$stmt = $pdo->prepare($sql);
$res = $stmt->execute(['id' => $id]);
/* Check the number of rows that match the SELECT statement */
if ($res) {
// success
$response["success"] = 1;
$response["data"] = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data = array();
$data["id"] = $row["ID"];
$data["state"] = $row["State"];
$data["state_abbrev"] = $row["StateAbbrev"];
$data["city"] = $row["City"];
array_push($response["data"], $data);
}
}
else {
/* No rows matched -- do something else */
// required field is missing
$response["success"] = 0;
$response["message"] = "No data returned!!";
}
}
else {
$response["success"] = 0;
$response["message"] = "Parameters are not correct";
}
// echoing JSON response
echo json_encode($response);
?>
This way I always get a response. I also use int responses for my "success" Tag. That way I can differentiate in my client code what went wrong in by checking the intvalue instead of trying to decipher the string response.
Notice that I am also using PDO with Prepared Statements. I highly recommend that you also use Prepared Statements to prevent SQL Injection.
I fixed it with initializing the array at the start of the php file. It normallt works without in my other php files and I dont know why it fixed my problem but it did.
Thanks for the answers anyway!
Do you see any reasons why it worked this way?

Android PostResponseAsyncTask cant get string from android

I have this application where I use PHP and Mysql for my queries in android studio but when im using update its not working the php should give me the string of what the $result gives me but its not giving any its blank.
Here are my codes.
Android
HashMap postData = new HashMap();
if (TextUtils.isEmpty(etCarModel.getText().toString())) {
Toast.makeText(UpdateClick.this, "Car model is empty", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(etCarType.getText().toString())) {
Toast.makeText(UpdateClick.this, "Car type is empty", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(etCapacity.getText().toString())) {
Toast.makeText(UpdateClick.this, "Capacity is empty", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(etPlateNumber.getText().toString())) {
Toast.makeText(UpdateClick.this, "Plate Number is empty", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(etPrice.getText().toString())) {
Toast.makeText(UpdateClick.this, "Price is empty", Toast.LENGTH_SHORT).show();
return;
}
postData.put("txtCar_No", tvCar_No.getText().toString());
postData.put("txtCarModel", etCarModel.getText().toString());
postData.put("txtCarType", etCarType.getText().toString());
postData.put("txtCapacity", etCapacity.getText().toString());
postData.put("txtPlateNumber", etPlateNumber.getText().toString());
postData.put("txtCarPrice", etPrice.getText().toString());
postData.put("image", toString());
postData.put("txtFuelType", spFuelType.getSelectedItem().toString());
PostResponseAsyncTask taskUpdate = new PostResponseAsyncTask(UpdateClick.this, postData, new AsyncResponse() {
#Override
public void processFinish(String q) {
Log.d(TAG,q);
if(q.contains("success")){
Toast.makeText(UpdateClick.this, "Car details updated!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(UpdateClick.this, OwnerTabs.class);
startActivity(in);
finish();
}else{
Toast.makeText(getApplicationContext(), "Error ? " + q.toString(), Toast.LENGTH_SHORT).show();
}
}
});
taskUpdate.execute("http://carkila.esy.es/update.php");
}
PHP
<?php
include_once("connection.php");
if(isset($_POST['txtCar_No']) && isset($_POST['txtCarModel']) &&
isset($_POST['txtCarType']) && isset($_POST['txtCapacity']) &&
isset($_POST['image']) && isset($_POST['txtFuelType']) &&
isset($_POST['txtPlateNumber']) && isset($_POST['txtcarPrice']))
{
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = $now->format('YmdHis');
$upload_folder = "upload";
$path = "$upload_folder/$id.jpeg";
$fullpath = "http://carkila.esy.es/$path";
$image = $_POST['image'];
$Car_No = $_POST['txtCar_No'];
$Car_Model = $_POST['txtCarModel'];
$Car_Type = $_POST['txtCarType'];
$Capacity = $_POST['txtCapacity'];
$Fuel_Type = $_POST['txtFuelType'];
$PlateNumber = $_POST['txtPlateNumber'];
$carPrice = $_POST['carPrice'];
$query = "UPDATE tbl_cars SET Car_Model='$Car_Model', Car_Type='$Car_Type', Capacity='$Capacity', Image='$fullpath', fuelType='$Fuel_Type',carPlatenuNumber='$PlateNumber' ,carPrice= '$carPrice' WHERE 'Car_No'=$Car_No";
$result = mysqli_query($conn,$query);
$count = mysqli_affected_rows($conn);
if($result == TRUE && $count > 0){
echo "success";
exit();
}else{
print_r (mysqli_error($conn));
echo "failed";
exit();
}
}
?>
i am from mobile, but try to change $result:
$result = mysqli_query($conn,$query);
With this:
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
EDIT:
You have to check whether the information is sent, so try to insert it to your code:
$filename = "log.txt";
$fh = fopen($filename, "a") or die("Could not open log file.");
$post = var_dump($post);
fwrite($fh, date("d-m-Y, H:i")." - $post\n") or die("Could not write file!");
fclose($fh);
Dont forget to create a log.txt file with chmod 777

Getting a response from a php script call

I have an app that sends some information via POST to a php script in a server. It uses Asynchttpclient. How can I also receive a reply back from the server (via json?)? Please help.
This is my php script
if($_POST["mode"]=="newuser"){
//$gcmRegID = $_GET["shareRegId"];
$gcmRegID = $_POST["regID"];
$gcmUserName = $_POST["userName"];
$gcmFolderName = $_POST["folderName"];
$gcmDate = date("d/m/y");
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$in_user = "user";
$in_password = "NULL";
$in_email = "NULL";
$in_dob = "NULL";
$in_role = "user";
$in_datejoined = "0000-00-00";
$foldername = "NULL";
$sql = "INSERT INTO user(password,regid,name,email,phone,dob,role,datejoined,foldername) VALUES('$in_password','$gcmRegID','$gcmUserName','$in_email','$in_phone','$in_dob','$in_role','$gcmDate','$foldername')";
$substringtitle = substr($gcmRegID,-7);
$combined = $gcmUserName."_".$substringtitle;
if($conn->query($sql)===TRUE){
mkdir("./users/".$gcmFolderName);
$newfoldername = "./users/".$gcmFolderName;
$updatequery = "UPDATE user SET foldername='$newfoldername' WHERE name='$gcmUserName'";
$returnfield = array(
'foldername' => $newfoldername
);
header('Content-type: application/json');
echo json_encode(array('returnfield'=>$returnfield));
if($conn->query($updatequery)===TRUE){
echo "folder updated";
}
//echo "Folder created!";
//}
echo "New record created successfully";
}else{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
echo "Done!";
exit;
}
Android code
//store in the file server (PHP)
private void storeREG(final String registerID,String userName,String folderName){
pg.show();
params.put("regID", registerID);
params.put("userName",userName);
params.put("folderName", folderName);
params.put("mode","newuser");
Log.d("STORE","STORE");
//Make RESTful webservice call
AsyncHttpClient client = new AsyncHttpClient();
client.post(AppConstants.SERVER_URL, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String content) {
pg.hide();
if (pg != null) {
pg.dismiss();
}
Toast.makeText(applicationCtx, "ID sharing successful", Toast.LENGTH_LONG).show();
Intent home = new Intent(applicationCtx, HomeActivity.class);
home.putExtra("regID", registerID);
Log.d("REGID", registerID);
startActivity(home);
finish();
}
#Override
public void onFailure(int statusCode, Throwable error, String content) {
pg.hide();
if (pg != null) {
pg.dismiss();
}
Log.d("ERRORTHROW", error.toString());
if (statusCode == 404) {
Toast.makeText(applicationCtx, "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(applicationCtx, "Something went wrong at the server", Toast.LENGTH_LONG).show();
} else {
Log.d("SHOWME", String.valueOf(statusCode));
Toast.makeText(applicationCtx, "Unexpected error occurred", Toast.LENGTH_LONG).show();
}
}
});
}
Hopefully I can get help with this.
You may try to revise your PHP Code. Below is a well-commented sample code to get you started:
<?php
// EXPLICITLY INSTRUCT THE HEADER ABOUT THE CONTENT TYPE. HERE - JSON
header('Content-type: application/json');
if($_POST["mode"]=="newuser"){
$gcmRegID = htmlspecialchars(trim($_POST["regID"]));
$gcmUserName = htmlspecialchars(trim($_POST["userName"]));
$gcmFolderName = htmlspecialchars(trim($_POST["folderName"]));
$gcmDate = date("d/m/y");
// I WOULD STRONGLY SUGGEST YOU USE PDO FOR YOUR DATABASE TRANSACTIONS:
// HERE'S HOW:
//DATABASE CONNECTION CONFIGURATION:
defined("HOST") or define("HOST", "localhost"); //REPLACE WITH YOUR DB-HOST
defined("DBASE") or define("DBASE", "database"); //REPLACE WITH YOUR DB NAME
defined("USER") or define("USER", "root"); //REPLACE WITH YOUR DB-USER
defined("PASS") or define("PASS", "root"); //REPLACE WITH YOUR DB-PASS
// ESTABLISH A CONNECTION AND DO YOUR WORK WITHIN A TRY-CATCH BLOCK...
try {
$dbh = new PDO('mysql:host='.HOST.';dbname='. DBASE,USER,PASS);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// HERE: ALL YOUR BUSINESS LOGIC...
$in_user = "user";
$in_password = "NULL";
$in_email = "NULL";
$in_phone = "NULL";
$in_dob = "NULL";
$in_role = "user";
$in_dateJoined = "0000-00-00";
$folderName = "NULL";
$insertSQL = "INSERT INTO user(`password`, `regid`, `name`, `email`, `phone`, `dob`, `role`, `datejoined`, `foldername`) ";
$insertSQL .= " VALUES(:inPassword, :gcmRegID, :gcmUserName, :inEmail, :inPhone, :inDOB, :inRole, :gcmDate, :folderName)";
$arrInsertData = array(
'inPassword' => $in_password,
'gcmRegID' => $gcmRegID,
'gcmUserName' => $gcmUserName,
'inEmail' => $in_email,
'inPhone' => $in_phone,
'inDOB' => $in_dob,
'inRole' => $in_role,
'gcmDate' => $gcmDate,
'folderName' => $folderName
);
// PREPARE THE INSERT QUERY:
$insertStmt = $dbh->prepare($insertSQL);
// INSERT THE NEW ROW:
$insertStmt->execute($arrInsertData);
// OBTAIN THE ID OF THE INSERTED ROW TO BE USED AS SUFFIX FOR YOUR USER FOLDER
$id = $dbh->lastInsertId();
// WHAT HAPPENS WHEN 2 USERS HAVE THE SAME USERNAME??? DID YOU THINK ABOUT THAT?
// TO CIRCUMVENT THIS ISSUE; I WOULD SUGGEST FIRST TO INSERT THE DATA TO THE DATABASE...
// THEN USE THE ID AS A SUFFIX TO MAKE EACH USER DIRECTORY UNIQUE & THAT IS THE APPROACH TAKEN HERE THOUGH...
// NOW YOU CAN CREATE YOUR FOLDER USING THIS ID: $id
// LIKE THIS; 2 USERS WITH USERNAME "android_user" CAN HAVE 2 DIFFERENT FOLDERS LIKE SO: "android_user_97" & "android_user_102"
$userDirectory = "./users/" . $gcmFolderName . "_" . $id;
mkdir($userDirectory);
// DID IT OCCUR TO YOU THAT 2 USERS MIGHT HAVE THE SAME USERNAME IN WHICH CASE MYSQL (INSTEAD OF YOU) HAS TO DECIDE WHICH USER TO UPDATE?
// THAT IS WHY DATABASE TABLES ARE DESIGNED TO HAVE UNIQUE IDENTIFIERS LIKE UUID OR ID OR UID OR ANY TOKEN TO MAKE EACH ROW UNIQUE...
// WE ARE ADOPTING THIS APPROACH IN THE UPDATE QUERY... THAT IS: WE UPDATE THE ROW USING THE ID ABOVE... ASSUMING THAT IS A UNIQUE COLUMN THOUGH.
$updateSQL = "UPDATE user SET foldername=:newDirName WHERE id=:ID";
// NOW UPDATE THE ROW TO TAKE INTO ACCOUNT THE UNIQUE USER-DIRECTORY (USING THE ID AS THE KEY)
$arrUpdateData = array(
'newDirName' => $userDirectory,
'ID' => $id // THIS ASSUMES THAT THE PRIMARY KEY OF YOUR TABLE IS CALLED id OTHERWISE USE THE APPROPRIATE KEY NAME: EG: reg_id OR WHATEVER
);
// PREPARE THE UPDATE QUERY:
$insertStmt = $dbh->prepare($updateSQL);
// UPDATE THE NEWLY CREATED ROW:
$insertStmt->execute($arrUpdateData);
// BUILD THE RESPONSE JSON DATA
$arrResponse = array(
'folderName' => $userDirectory,
'id' => $id,
);
// SEND THE RESPONSE AS JSON IF ALL WORKS FINE TILL HERE...
// THAT MEANS: SEND THE DATA IN $arrResponse AND TERMINATE THE SCRIPT - THE JOB IS DONE.
// NO NEED FOR ALL THOSE ECHO STATEMENTS AS THE YOU ARE EXPLICITLY SENDING BACK JSON DATA.
die( json_encode($arrResponse) );
}catch(PDOException $e){
// IF THERE WAS ANY KIND OF PDO ERROR, SEND IT BACK ANYWAYS - BUT ALSO AS JSON:
$arrResponse = array(
'error' => $e->getMessage()
);
die( json_encode($arrResponse) );
}
}
I can't test the code right now (sorry), but I think it should be something like this:
try {
RequestParams rParams = new RequestParams();
rParams.put("example", "example"); // POST
AsyncHttpClient client = new AsyncHttpClient();
client.get(pageURL, rParams, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONArray jsonArray) {
super.onSuccess(jsonArray);
//process JSON Array
}
#Override
public void onFailure(Throwable throwable, JSONArray jsonArray) {
super.onFailure(throwable, jsonArray);
Log.d(TAG, "error", throwable);
}
});
} catch (Exception e) {
Log.d(TAG, "exception", e);
}
Otherwise I made a very light WebClient, you may want to give it a shot:
https://github.com/omaflak/WebClient
This is a short sample:
WebClient client = new WebClient();
client.setOnRequestListener(new OnRequestListener() {
#Override
public void onRequest(String response, int requestID) {
Log.e(TAG, response);
}
#Override
public void onError(int error_code, String message) {
Log.e(TAG, message);
}
});
Pair p = new Pair("field1", "value1");
Pair p2 = new Pair("field2", "value2");
client.requestAsync("http://your-api.com", WebClient.POST, Arrays.asList(p, p2), 1);
// requestAsync(String url, String method, List<Pair<String, String>> postData, int requestID)
To use it, simply add to your dependencies:
compile 'me.aflak.libraries:webclient:1.0'

Categories