How to execute PHP query (without arguments) from android - php

how could I invoke this code:
<?php
//load and connect to MySQL database stuff
require("config.inc.php");
$query_params = null;
$resetQuery = "UPDATE `items` SET `picked`= 0";
try {
$stmt = $db->prepare($resetQuery);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "PHP Database Error!";
die(json_encode($response));
}
echo "DB reset complete";
?>
from android app?
Normally, when there are arguments to pass, I parse JSON object and post it as follows:
JSONObject json = jsonParser.makeHttpRequest(
RESET_DB, "POST", params);

Related

Cannot fetch the value from JsonArray

I am having problem fetching out the value from PHP coding to my android. The logcat shows that
:W/System.err: org.json.JSONException:
No value for posts.
This is my php code:
<?php
require("config1.php");
$query="SELECT commentName,comment FROM discussion_comment WHERE discussID = :discussID";
$query_params=array(':discussID'=> $_POST['discussID']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows){
$response["success"]=1;
$response["message"]="Post Available";
$response["posts"]= array();
foreach ($rows as $row){
$post = array();
$post["commentName"] = $row["commentName"];
$post["comment"] = $row["comment"];
array_push($response["posts"], $post);
}
echo json_encode($response);
}else {
$response["success"] = 0;
$response["message"] = "No post Available!";
die(json_encode($response));
?>
When is remove the 'WHERE discussID = :discussID"', I am able to fetch the data, but some is not necessary. What other way to write with Where condition.
My java:
private static final String COMMENT_NAME="commentName";
private static final String COMMENT="comment";
private static final String COMMENT_VIEW_URL="http://fysystem.com/show_comment.php";
#Override
protected String doInBackground(String... args) {
try {
json=jsonParser.getJSONFromUrl(COMMENT_VIEW_URL);
JSONArray jsonArray=json.getJSONArray("posts");
for(int i = 0; i<jsonArray.length();i++) {
json=jsonArray.getJSONObject(i);
commentName=json.getString(COMMENT_NAME);
comment=json.getString(COMMENT);
}
Appreciate your help.
PHP
<?php
require("config1.php");
// Default message
$response = array('success'=>0, 'message'=>'Error. Pass required parameters');
// Check discussID exists in POST params
if(isset($_POST['discussID']) && $_POST['discussID']!=""){
$sql = 'SELECT `commentName`, `comment` FROM `discussion_comment` WHERE `discussID` = :discussID';
try {
// Hope $db is defined in config1.php
$stmt = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute(array(':discussID'=> $_POST['discussID']));
$response = array("success"=>0, "message"=>"Discussion Not found");
// If data exists
if($stmt->rowCount()>0){
// Fetching rows with a scrollable cursor
// http://php.net/manual/en/pdostatement.fetch.php
$posts = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$posts[] = array('commentName'=>$row['commentName'], 'comment' => $row['comment']);
}
// Set the success status 1 and add the posts in return response
$response = array('success'=>1, 'message'=>'Discussion found', 'posts'=>$posts);
}
$stmt = null;
}
catch (PDOException $e) {
// print $e->getMessage();
$response = array('success'=>0, 'message'=>'DB Error');
}
}
// Finally return the response
echo json_encode($response);
?>
Andorid
try {
json=jsonParser.getJSONFromUrl(COMMENT_VIEW_URL);
int success = json.getInt('success');
// Check before access posts data
if(success==1){
JSONArray jsonArray=json.getJSONArray("posts");
for(int i = 0; i<jsonArray.length();i++) {
json=jsonArray.getJSONObject(i);
commentName=json.getString(COMMENT_NAME);
comment=json.getString(COMMENT);
}
}else{
// Handle it here if parameters not exist or db error or no discussion found
}
}
Hope this helps!

Insert data into server

I have problem inserting data into my database. The data can't be inserted and it does not show any errors in my Logcat. I have working on it but still can't solve the problems. This is my PHP code:
<?php
require ("config1.php");
if(!empty($_POST)){
$query = "SELECT * FROM announcement WHERE announceID = :announcementID";
$query_params=array(':announcementID'=> $_POST['announcementID']);
try{
$stmt=$db->prepare($query);
$stmt->execute($query_params);
}catch(PDOException $ex){
$response["success"]=0;
$response["message"]="Database Error1. Please try again";
die(json_encode($response));
}
$row = $stmt->fetch();
if($row){
$query = "INSERT INTO announcement (title,description,start_date,end_date,time)
VALUES (:title,:description,:starDate,:endDate,:time) ";
$query_params= array(
':title'=>$_POST['title'];
':description'=>$_POST['description'];
':startDate' => $_POST['start_date'];
':endDate' => $_POST['end_date'];
':time' => $_POST['time'];
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error2. Please Try Again!";
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Update successful!";
echo json_encode($response)
}
}
?>
Below is my java code:
protected String doInBackground(Void... params) {
RequestHandler rh=new RequestHandler();
HashMap<String,String> param= new HashMap<String, String>();
param.put(KEY_TITLE,announcement_title);
param.put(KEY_DESCRIPTION,announcement_desc);
param.put(KEY_START_DATE,start_date);
param.put(KEY_END_DATE,end_date);
param.put(KEY_TIME,time);
param.put(KEY_IMAGE,announcement_image);
String result= rh.sendPostRequest(ANNOUNCEMENT_URL,param);
return result;
}
Appreciate is someone can point out the problems.
You PHP Code Has Syntax error and Mysql preparement Placeholder error.
I Have Rewritten the Code kindly replace with your Old Code.
<?php
require ("config1.php");
if(!empty($_POST)){
//kindly filter the POST value
$query = "SELECT * FROM announcement WHERE announcementID = :announcementID";
$query_params=array(':announcementID'=> $_POST['announcementID']);
$stmt=$db->prepare($query);
$stmt->execute($query_params);
/*
}catch(PDOException $e){
$response["success"]=0;
$response["message"]="Database Error1. Please try again";
die(json_encode($response));
}
*/
$row = $stmt->fetch();
if($row){
$query = "INSERT INTO announcement (title,description,start_date,end_date,time)
VALUES (:title,:description,:starDate,:endDate,:time)";
//re written by Ajmal PraveeN
$query_params= array(
':title'=>$_POST['title'],
':description'=>$_POST['description'],
':startDate' => $_POST['start_date'],
':endDate' => $_POST['end_date'],
':time' => $_POST['time']
);
/*
try {
*/
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
/*
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error2. Please Try Again!";
die(json_encode($response));
}
*/
$response["success"] = 1;
$response["message"] = "Update successful!";
echo json_encode($response);
}
}
?>
If your $_POST['announcementID'] is a numeric number i can re edit the post with a Sanitize and Title post too.

Sending/retriving arabic charecters (utf8) using json from android to server

I'm trying to store Arabic characters in a database on server. But when I add something it will be displayed as ???????????? in the database! I tried too add from my php to check if the problem from the php file, but it added the text correctly in database. So the error from android and json, how can I make the encoding of json to utf8 in android?
Here's my code:
class AddStories extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Caregiver_ID", ID));
params.add(new BasicNameValuePair("Title", "قصة"));
params.add(new BasicNameValuePair("Story", "قصتي بدأت عندما"));
JSONObject json = jsonParser.makeHttpRequest(url_add_story,"POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
suc=1;
sucess();
}
else {
suc=0;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
PHP for adding:
<?php
header("Content-Type: text/html; charset=utf-8");
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['Caregiver_ID']) && isset($_POST['Title'])&& isset($_POST['Story'])) {
$Caregiver_ID = $_POST['Caregiver_ID'];
$Title = $_POST['Title'];
$Story = $_POST['Story'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
mysql_query("SET NAMES 'utf8'"); mysql_query('SET CHARACTER SET utf8');
// mysql inserting a new row
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', '$Title','$Story')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "glossary successfully created.";
// echoing JSON response
echo json_encode($response,JSON_UNESCAPED_UNICODE );
} 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 );
}
?>
Also when I tried to retrieve from android I got this for the text:
نةيىؤتيلالاؤتيلاارلابارابي-الالالتعا
while its retrieved correctly in php.
PHP code
<?php
header("Content-Type: text/html; charset=utf-8");
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT *FROM Stories ") or die(mysql_error());
mysql_query("SET NAMES 'utf8'"); mysql_query('SET CHARACTER SET utf8');
if (mysql_num_rows($result) > 0) {
$response["story"] = array();
while ($row = mysql_fetch_array($result)) {
$story = array();
$story ["Caregiver_ID"] = $row["Caregiver_ID"];
$story ["Title"] = mb_convert_encoding($row["Title"],'HTML-ENTITIES','utf-8');
$story ["Story"] = mb_convert_encoding($row["Story"],'HTML-ENTITIES','utf-8');
array_push($response["story"], $story);
}
$response["success"] = 1;
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No locations found";
// echo no users JSON
echo json_encode($response);
}
?>
Try below code in android
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
byte[] buffer = new byte[1024];
int nread;
while ((nread = stream.read(buffer)) > 0) {
baos.write(buffer, 0, nread);
}
} catch (ClientProtocolException | IOException e) {
}
//Create a JSON from the String that was return.
JSONObject jsonObject = new JSONObject();
try {
String jsonText = new String(baos.toByteArray(), StandardCharsets.UTF_8);
jsonObject = new JSONObject(jsonText);
You have to put N before the columns which you need to add the Arabic text.
For example N'مختار'.
According to your code,you should change this line
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', '$Title','$Story')");
........
.....
...
to be
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', N'$Title',N'$Story')");

Error in php code.Maybe my for loop is wrong?

ok i am not familiar with php but i have to use it for my android application to take data from mysql server.This is what i ve done so far.When i call this script from the app i want to create a new booking row and all the booked seat rows that the user selected . The above php throws an exception but i dont know where.
<?php
#open connection
require("config.inc.php");
//if posted data is not empty
if (!empty($_POST)) {
$query = "INSERT INTO booking (show_id) VALUES (:showId) ";
$query_params = array(
':showId' => $_POST['showId']);
$query_params1 = array(
':seatNo' => $_POST['seatNo']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$lastRow = $db->lastInsertId('booking');
for($i=0; $i<$_POST['size']; $i++){
$query1 = "INSERT INTO booked_seats (booking_id,seat) VALUES ($lastRow,:seatNo) ";
$query_params1 = array(
':seatNo' => $_POST["seat{$i}"]);
$stmt = $db->prepare($query1);
$result = $stmt->execute($query_params1);
}
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error. Please Try Again!";
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Reservation Completed!";
echo json_encode($response);
}
?>
and this is the java code where i call the php
protected String doInBackground(String... strings) {
String msg=null;
try {
List<NameValuePair> params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("showId", showId));
params.add(new BasicNameValuePair("size",Integer.toString(selectedSeats.size())));
for(int i=0; i<selectedSeats.size(); i++) {
params.add(new BasicNameValuePair("seat"+Integer.toString(i),Integer.to String(selectedSeats.get(i))));
}
JSONObject jsonObject=jsonParser.makeHttpRequest( LOGIN_URL, "POST", params);
msg = jsonObject.getString(TAG_MESSAGE);
}
catch (JSONException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
return msg;
}
I know that the tag seat* that i use may be a little bit unusual but i couldnt think anything else.
The weird think is that the above code works.It makes the changes in the database but the msg
"Reservation Completed! is never reachable because it throws an exception somewhere!
Try using the following to echo the json:
header('Content-Type: application/json');
echo json_encode($response);
Also, ommit the PHP closing tag ?>. Last but not least; make sure nothing else is being sent to output before echo-ing your JSON.
Complete answer:
<?php
#open connection
require("config.inc.php");
//if posted data is not empty
if (!empty($_POST)) {
$query = "INSERT INTO booking (show_id) VALUES (:showId) ";
$query_params = array(
':showId' => $_POST['showId']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
$lastRow = $db->lastInsertId('booking');
for($i=0; $i<$_POST['size']; $i++){
$query1 = "INSERT INTO booked_seats (booking_id,seat) VALUES ($lastRow,:seatNo) ";
$query_params1 = array(
':seatNo' => $_POST["seat" . $i]);
$stmt = $db->prepare($query1);
$result = $stmt->execute($query_params1);
}
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error. Please Try Again!";
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Reservation Completed!";
header('Content-Type: application/json');
echo json_encode($response);
}

Error in php script when hosted in the remote server only

I have an android app with php backend, the problem is one of the php scripts works perfectly on the local server while when online it does not and produce the following error:
Parse error: syntax error, unexpected '"', expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/malblbic/public_html/webservice/profile.php on line 23
Here is my php code.
<?php
/*
Our "config.inc.php" file connects to database every time we include or require
it within a php script. Since we want this script to add a new user to our db,
we will be talking with our database, and therefore,
let's require the connection to happen:
*/
require("config.inc.php");
//initial query
$username = $_POST['username'];
$query = "Select * FROM users;
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response[‘success’] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "User Available!";
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["picture"] = $row["picture"];
$post["username"] = $row["username"];
$post["points"] = $row["points"];
//update our repsonse JSON data
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Users Available!";
die(json_encode($response));
}
?>
Change backticks to regular quotes
$response[‘success’] = 0;
To
$response['success'] = 0;

Categories