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
Related
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)
}
}
}
I am creating an app for which I have to maintain a table(login registration), for connecting my android app to the table I am using PHP.
Android code
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegisterActivity.this, Login.class);
RegisterActivity.this.startActivity(intent);
} else if(!success)
{ JSONObject jsonResponse2 = new JSONObject(response);
String errval = new String();
errval=jsonResponse2.getString("errval");
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage(errval)
.setNegativeButton("retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error submitting registration", Toast.LENGTH_SHORT).show();
}
PHP code:-
require 'config.php';
$file = 'outfile.txt';
if ($_POST) {
file_put_contents($file,"~~~~~~~~~~~~~~~~~~~~\n");
foreach ($_POST as $KEY => $VAL) {
file_put_contents($file,$KEY."=>".$VAL."\n", FILE_APPEND);
}
if (#$_POST["Email_id"] and #$_POST["hash"]) {
$email = strtolower($_POST["Email_id"]);
$username = strtolower($_POST["Username"]);
$hash = $_POST["hash"];
$echk = $my->Execute("select count(*) from users where email = '$email'");
if ($echk->fields[0] == 0) {
$uchk = $my->Execute("select count(*) from users where user = '$username'");
if ($uchk->fields[0] == 0) {
$ins = $my->Execute("insert into users values (default,'$username','$email','$hash',default)");
$error["success"] = true;
$error["errval"] = "success";
file_put_contents($file,"success", FILE_APPEND);
} else {
$error["success"] = false;
$error["errval"] = "User: $username already exists";
}
} else {
$error["success"] = false;
$error["errval"] = "Email: $email already exists";
}
} else {
$error["errval"] = "Missing a key: 'Email_id' or 'hash'";
}
file_put_contents($file,"~~~~~~~~~~~~~~~~~~~~\n", FILE_APPEND);
$json = json_encode($error);
print_r($json);
}
?>
The details are being entered in the DB without any issues every time, the code also shows if the email is aldready existing in the table, but if the registration is a success, the app throws exception Error submitting registration. cant figure out where the problem is
thank you.
PS. I am new to stackoverflow still learning, forgive if there are any mistakes in post
if (#$echk->fields[0] == 0) {
$uchk = $my->Execute("select count(*) from users where user = '$username'");
if (#$uchk->fields[0] == 0) {
$ins = $my->Execute("insert into users values (default,'$username','$email','$hash',default)");
$error["success"] = true;
$error["errval"] = "success";
file_put_contents($file,"success", FILE_APPEND);
forgot # in if condition
I made simple upload system with using class.upload.php and it works great while adding new into database. But i have problem when i need to edit my entry. While editing entry i don't want to edit image but it sent it blank, also if i select image again it sent it blank too. Here is my code.
Can explain my problem.
<?php require_once("conn.php");
require_once ("class.upload.php");
$catid = $_POST['catid'];
$title = $_POST['title'];
$descc = $_POST['descc'];
$keyw = $_POST['keyw'];
$message = $_POST['message'];
$Image = $_FILES['Image'];
$randnum = rand();
$foo = new upload($Image);
$filee = './Image';
if ($foo->uploaded) {
$foo->image_resize = true;
$foo->file_new_name_body = $randnum;
$foo->image_x = 550;
$foo->image_y = 440;
$foo->process($filee);
if ($foo->processed) {
echo 'Image uploaded.';
echo $foo->file_dst_name;
$foo->clean();
} else {
echo 'Error. : ' . $foo->error;
}
}
$Image7 = $foo->file_dst_name;
if($_GET[pass] == 1)
{
if(!isset($_POST[catid]) || empty($_POST[catid])){
$hata = "Required area.";
}
if(!isset($_POST[title]) || empty($_POST[title])){
$hata = "Required area.";
}
if(!isset($_POST[descc]) || empty($_POST[descc])){
$hata = "Required area.";
}
if(!isset($_POST[keyw]) || empty($_POST[keyw])){
$hata = "Required area.";
}
if(!isset($_POST[message]) || empty($_POST[message])){
$hata = "Required area.";
}
if(!$hata){
mysql_query("UPDATE product SET
catid='$_POST[catid]',
title='$_POST[title]',
descc='$_POST[descc]',
keyw='$_POST[keyw]',
message='$_POST[message]',
Image='$_POST[Image]'
WHERE id='$_POST[id]'
");
$mesaj = "OK!";
}
}
$sonuc = mysql_query("select * from product WHERE id='$_GET[product]'");
$edit = mysql_fetch_array($sonuc);
$sonuc1 = mysql_query("select * from category");
$edit1 = mysql_fetch_array($sonuc1);
?>
try to change the update query
at Image='$_POST[Image]'
with Image='$Image7'
Fatih you can use a variable (i.e. $saved_image_name) instead of $POST[Image] at sql query. Set this variable to new name if uploaded else old value of db field.
...
...
$foo = new upload($Image);
$filee = './Image';
$saved_image_name = " Image "; // name of db field.
if ($foo->uploaded) {
$foo->image_resize = true;
$foo->file_new_name_body = $randnum;
$foo->image_x = 550;
$foo->image_y = 440;
$foo->process($filee);
if ($foo->processed) {
echo 'Image uploaded.';
echo $foo->file_dst_name;
// Note the quotes
$saved_image_name = " '$foo->file_dst_name' ";
$foo->clean();
} else {
echo 'Error. : ' . $foo->error;
}
}
// no use anymore $Image7 = $foo->file_dst_name;
...
...
if(!$hata){
mysql_query("UPDATE product SET
catid='$_POST[catid]',
title='$_POST[title]',
descc='$_POST[descc]',
keyw='$_POST[keyw]',
message='$_POST[message]',
Image= $saved_image_name // note the quotes
WHERE id='$_POST[id]'
");
...
...
I have created a json for getting mysql data for a news app in android & ios. Whenever I am parsing the json.php file it returns "No tag defined" and the app stopped working both android and ios. Here is the code sample that I was trying to work out.
<?php
header('content-type: application/json; charset=utf-8');
$con = mysql_connect("localhost","####","###");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("###", $con);
$date = date('Y-m-d');
//$date = '2014-02-01';
$year = substr($date, 0, -6);
$month = substr($date, 5, -3);
$day = substr($date,-2, 10);
if($month==01) $month1="january";
else if($month==02) $month1="february";
else if($month==03) $month1="march";
else if($month==04) $month1="april";
else if($month==05) $month1="may";
else if($month==06) $month1="june";
else if($month==07) $month1="july";
else if($month==08) $month1="august";
else if($month==09) $month1="september";
else if($month==10) $month1="october";
else if($month==11) $month1="november";
else if($month==12) $month1="december";
$table=$month1.$year;
//$table = $february2014;
if(isset($_REQUEST['tag']) && $_REQUEST['tag'] != ''){
$tag = $_REQUEST['tag'];
if($tag =='category_page' && isset($_REQUEST['menu_id']) && $_REQUEST['menu_id'] !='' ) {
$menu_id = $_REQUEST['menu_id'];
try{
$i=0;
$query = mysql_query("SELECT * FROM $table WHERE menu_id=1 AND news_date ='$date'");
if($query === FALSE) {
die(mysql_error());
}
while($data=mysql_fetch_array($query)){
$responce[$i]['news_id'] = $data['news_id'];
$responce[$i]['news_title'] = str_replace("\t",'',str_replace("\r\n\t",'', substr(strip_tags($data['news_title']),0,110)));
$responce[$i]['news_reporter'] = str_replace("\t",'',str_replace("\r\n\t",'', substr(strip_tags($data['news_reporter']),0,110)));
$responce[$i]['news_details'] = str_replace("\t",'',str_replace("\r\n\t",'', substr(strip_tags($data['news_details']),0,110)));
$responce[$i]['photo'] = $data['photo'];
$responce[$i]['path'] = 'admin/'.str_replace('\\','',$data['path']);
$responce[$i]['menu_id'] = $data['menu_id'];
$responce[$i]['menu_type'] = $data['menu_type'];
$responce[$i]['news_publish_status'] = $data['news_publish_status'];
$responce[$i]['news_order'] = $data['news_order'];
$responce[$i]['news_date'] = $data['news_date'];
$responce[$i]['news_time'] = $data['news_time'];
$responce[$i]['added_by'] = $data['added_by'];
$responce[$i]['directory'] = $data['directory'];
$responce[$i]['read_number'] = $data['read_number'];
$responce[$i]['comment_number'] = $data['comment_number'];
$responce[$i]['news_comment_table_name'] = $data['news_comment_table_name'];
$i++;
}
} catch(Exception $e) {
$responce = 'Exception: '.$e->getMessage();
}
}else{
$responce = "category or Menu id is not Defined";
}
echo json_encode($responce);
}else{
echo json_encode("No tag Defined");
}
?>
not getting any way to fix it up. can any one help me out.Would appreciate your kind assistance.
Try this
if(isset($_REQUEST['tag'])){
Instead of
if(isset($_REQUEST['tag']) && $_REQUEST['tag'] != ''){
I have successfully fetched data from remote database using methods posted on internet.But I'm unable to push (insert) data into the same table.
I've added a static counter just to check whether the code reaches the given url, but as expected , it fails.Below is the php file I've saved up in my remote server file manager.
<?php
$json=$_GET [ 'json']; $json=f ile_get_contents( 'php://input');
$obj=json_decode($json);
$conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting");
mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
error_reporting(E_ALL);
$tid=$_POST[ 'tid'];
$name=$_POST[ 'name'];
mysql_query( "insert into mytablename(tid,name) values($tid,$name)");
?>
I took two inputs in the android layout, tid, name and trying to send to remote database.
Note : database name and other details have been hidden for security purpose.
if your looking for a clean way ..i suggest you to do something like this :
register.php
<?php
include('connect.php');
$response = array();
if (isset($_POST['Nom']) && isset($_POST['Prenom']) && isset($_POST['Email'])&& isset($_POST['Mdp'])) { //checking if the required fields are set
$Nom = $_POST['Nom'];//the family name
$Prenom = $_POST['Prenom']; //last name
$Email = $db->real_escape_string($_POST['Email']);
$Mdp = $db->real_escape_string($_POST['Mdp']); //the password
if ($res = $db->query("SELECT * FROM `patient` WHERE `Email_p`='$Email' ")) {
$row_cnt = $res->num_rows; }
if($row_cnt>0) {
$response["success"] = 0;
$response["message"] = "Email exists"; }
if ($row_cnt <1){
$result = mysqli_query($db,"INSERT INTO `patient`(`Id_p`, `Nom`, `Prenom`, `Email_p`, `Mdp`) VALUES ('','$Nom','$Prenom','$Email','$Mdp')");
if ($result ) {
$response["success"] = 1; // if account created we set success value to 1
$response["message"] = "account created";
} else {
$response["success"] = 0;
$response["message"] = "Oops Error";
}}
}else {
$response["success"] = 0;
$response["message"] = "Fields messing";
}
echo json_encode($response);
?>
in android ... yourActivity.java
class CreerNouveauCompte extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(inscription.this);
pDialog.setMessage(getString(R.string.inscriEnCours));
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String nom = edtNom.getText().toString();
String prenom = edtPrenom.getText().toString();
String email = edtEmail.getText().toString();
String mdp = edtMdp.getText().toString();
JSONObject json;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Nom", nom));
params.add(new BasicNameValuePair("Prenom", prenom));
params.add(new BasicNameValuePair("Email", email));
params.add(new BasicNameValuePair("Mdp", mdp));
json= jsonParser.makeHttpRequest(url_register (your url),
"POST", params);
}
try {if(json != null && !json.isNull("success")){
int success = json.getInt("success");
s2=json.getString("message");
if (success == 1) { //the acount created
Intent intent;
SharedPreferences settings = getSharedPreferences("compte", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("nom",edtNom.getText().toString() );
editor.putString("prenom",edtPrenom.getText().toString() );
editor.putString("email",edtEmail.getText().toString());
editor.putString("mdp",edtMdp.getText().toString());
editor.apply();
intent = new Intent(inscription.this,MainActivity.class);
}
startActivity(intent);
finish();
} else {
}}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
call it like this
new CreerNouveauCompte().execute();
the connect.php
<?php
$db = new mysqli('localhost', 'root', '', 'rechmed');
mysqli_set_charset($db,'utf8');
?>
//note i use mysqli ..in your case use mysql
Use the code below if you are trying to decode a JSONObject with this format {"tid":"myTidValue", "name":"myNameValue"}
<?php
$json=stripslashes($_GET['json']);
$obj=json_decode($json, true);
$conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting");
mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
error_reporting(E_ALL);
$tid=$json['tid'];
$name=$json['name'];
mysql_query("insert into mytablename(tid,name) values('$tid','$name')");
?>
and to decode a JSONArray with this format [{"tid":"myTidValue1", "name":"myNameValue1"}, {"tid":"myTidValue2", "name":"myNameValue2"}] you can use below code
<?php
$json=stripslashes($_GET['json']);
$obj=json_decode($json, true);
$conn=mysql_connect( "mydatabasename", "myusername", "mypassword") or die( "error connecting");
mysql_select_db( "mydatabasename",$conn)or die("database couldnot connect");
error_reporting(E_ALL);
foreach ($json as $data){
$tid=$data['tid'];
$name=$data['name'];
mysql_query("insert into mytablename(tid,name) values('$tid','$name')");
}
?>
if neither works, post your codes for android